core

package
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 8, 2026 License: MIT Imports: 13 Imported by: 0

README

Core Package

The core package defines the fundamental domain models, interfaces, and cryptographic utilities for the Clearnode protocol. It serves as the single source of truth for shared data structures between the node, client, and smart contract interactions.

Overview

Key Features
  • Domain Models: Standardized structures for Channels, States, Transitions, and Ledgers.
  • On-chain Events: Type-safe definitions for Home and Escrow channel lifecycle events.
  • Cryptographic Utilities: Deterministic ID generation for channels, states, and transactions using Keccak256 and ABI packing.
  • Validation: Interface and implementation for state transition logic (e.g., version increments, epoch tracking).
  • Abstractions: Clean interfaces for Blockchain Clients and Event Listeners.

Core Components

Channel Lifecycle

The protocol distinguishes between two types of channels:

  1. Home Channel: The primary settlement layer between a user and a node.
  2. Escrow Channel: Temporary channels used for cross-chain or specific deposit/withdrawal operations.
State Management

The State struct represents a snapshot of the off-chain ledger. Every state update must include:

  • A version increment.
  • At least one Transition (Transfer, Deposit, Withdrawal, etc.).
  • Valid signatures from both the User and the Node.
Identification & Hashing

The package provides deterministic hashing utilities to ensure consistency between off-chain logic and on-chain Smart Contracts:

Method Description
GetHomeChannelID Hashes node, user, token, nonce, and challenge period.
GetEscrowChannelID Derives an ID from a Home Channel ID and a state version.
GetStateID Generates a unique hash for a specific state snapshot.
GetTransactionID Creates a unique reference for individual transfers or adjustments.

Interface Definitions

Client Interface

The Client interface abstracts the communication with the ChannelsHub smart contract:

  • Vault Operations: Deposit, Withdraw, and GetAccountsBalances.
  • Channel Operations: Create, Checkpoint, Challenge, and Close.
  • Escrow Operations: Initiation and Finalization of Escrow deposits and withdrawals.
Listener Interface

The Listener allows applications to react to on-chain state changes by registering handlers for events like HomeChannelCreatedEvent or EscrowDepositFinalizedEvent.

State Advancer

The StateAdvancer ensures that off-chain state updates follow the protocol rules.

advancer := core.NewStateAdvancerV1()
err := advancer.ValidateAdvancement(oldState, newState)
// Checks: Version increment, ledgers, epoch consistency, signature presence, etc.

Data Structures

Transaction Types

Transactions are categorized to handle specific ledger movements:

  • Home/Escrow: Deposit, Withdrawal and Migration.
  • Operations: Transfers, Commits, Releases.
  • Locking: Escrow and Mutual locks for cross-chain safety.
Ledger

The Ledger tracks balances and "Net Flow" (total funds inflow(+)/outflow(-) of the channel) for both the user and the node within a specific channel context.

Usage Example: Generating IDs

import "github.com/layer-3/nitrolite/core"

// Generate a Home Channel ID
channelID, err := core.GetHomeChannelID(
    nodeAddr, 
    userAddr, 
    tokenAddr, 
    nonce, 
    7*24*3600, // challenge
)

// Generate a State ID for a new update
stateID, err := core.GetStateID(userWallet, "eth", epoch, version)

Documentation

Index

Constants

View Source
const (
	INTENT_OPERATE                    = 0
	INTENT_CLOSE                      = 1
	INTENT_DEPOSIT                    = 2
	INTENT_WITHDRAW                   = 3
	INTENT_INITIATE_ESCROW_DEPOSIT    = 4
	INTENT_FINALIZE_ESCROW_DEPOSIT    = 5
	INTENT_INITIATE_ESCROW_WITHDRAWAL = 6
	INTENT_FINALIZE_ESCROW_WITHDRAWAL = 7
	INTENT_INITIATE_MIGRATION         = 8
	INTENT_FINALIZE_MIGRATION         = 9
)
View Source
const (
	// ChannelHubVersion is the version of the ChannelHub contract that this code is compatible with.
	// This version is encoded as the first byte of the channelId to prevent replay attacks
	// across different ChannelHub deployments on the same chain.
	ChannelHubVersion uint8 = 1
)

Variables

Functions

func BuildSigValidatorsBitmap

func BuildSigValidatorsBitmap(signerTypes []ChannelSignerType) string

BuildSigValidatorsBitmap constructs a hex string bitmap from a slice of ChannelSignerType. Each signer type sets a bit at its corresponding position in a 256-bit value.

func DecimalToBigInt

func DecimalToBigInt(amount decimal.Decimal, decimals uint8) (*big.Int, error)

DecimalToBigInt converts a decimal.Decimal amount to *big.Int scaled to the token's smallest unit. For example, 1.23 USDC (6 decimals) becomes 1230000. This is used when preparing amounts for smart contract calls.

func GenerateChannelMetadata

func GenerateChannelMetadata(asset string) [32]byte

GenerateChannelMetadata creates metadata from an asset by taking the first 8 bytes of keccak256(asset) and padding the rest with zeros to make a 32-byte array.

func GenerateSessionKeyStateIDV1

func GenerateSessionKeyStateIDV1(userAddress, sessionKey string, version uint64) (string, error)

GenerateSessionKeyStateIDV1 generates a deterministic ID from user_address, session_key, and version.

func GetChannelSessionKeyAuthMetadataHashV1

func GetChannelSessionKeyAuthMetadataHashV1(version uint64, assets []string, expiresAt int64) (common.Hash, error)

func GetEscrowChannelID

func GetEscrowChannelID(homeChannelID string, stateVersion uint64) (string, error)

GetEscrowChannelID derives an escrow-specific channel ID based on a home channel and state version. This matches the Solidity getEscrowId function which computes keccak256(abi.encode(channelId, version)).

func GetHomeChannelID

func GetHomeChannelID(node, user, asset string, nonce uint64, challengeDuration uint32, approvedSigValidators string) (string, error)

GetHomeChannelID generates a unique identifier for a primary channel based on its definition. It uses the configured ChannelHubVersion to ensure compatibility with the deployed ChannelHub contract. The channelId includes version information to prevent replay attacks across different ChannelHub deployments.

func GetReceiverTransactionID

func GetReceiverTransactionID(fromAccount, receiverNewStateID string) (string, error)

GetReceiverTransactionID calculates and returns a unique transaction ID reference for actions initiated by node.

func GetSenderTransactionID

func GetSenderTransactionID(toAccount string, senderNewStateID string) (string, error)

GetSenderTransactionID calculates and returns a unique transaction ID reference for actions initiated by user.

func GetStateID

func GetStateID(userWallet, asset string, epoch, version uint64) string

GetStateID creates a unique hash representing a specific snapshot of a user's wallet and asset state.

func GetStateTransitionHash

func GetStateTransitionHash(transition Transition) ([32]byte, error)

func IsChannelSignerSupported

func IsChannelSignerSupported(approvedSigValidators string, signerType ChannelSignerType) bool

func PackChallengeState

func PackChallengeState(state State, assetStore AssetStore) ([]byte, error)

PackChallengeState is a convenience function that creates a StatePackerV1 and packs the challenge state.

func PackChannelKeyStateV1

func PackChannelKeyStateV1(sessionKey string, metadataHash common.Hash) ([]byte, error)

PackChannelKeyStateV1 packs the session key state for signing using ABI encoding. This is used to generate a deterministic hash that the user signs when registering/updating a session key. The user_sig field is excluded from packing since it is the signature itself.

func PackState

func PackState(state State, assetStore AssetStore) ([]byte, error)

PackState is a convenience function that creates a StatePackerV1 and packs the state. For production use, create a StatePackerV1 instance and reuse it.

func SignerValidatorsSupported

func SignerValidatorsSupported(channelValidators string) bool

SignerValidatorsSupported checks that every bit in channelValidators is covered by the node's supported ChannelSignerTypes.

func TransitionToIntent

func TransitionToIntent(transition Transition) uint8

func ValidateChannelSessionKeyAuthSigV1

func ValidateChannelSessionKeyAuthSigV1(state ChannelSessionKeyStateV1) error

func ValidateDecimalPrecision

func ValidateDecimalPrecision(amount decimal.Decimal, maxDecimals uint8) error

ValidateDecimalPrecision validates that an amount doesn't exceed the maximum allowed decimal places.

Types

type ActionAllowance

type ActionAllowance struct {
	GatedAction GatedAction
	TimeWindow  string
	Allowance   uint64
	Used        uint64
}

ActionAllowance represents the allowance information for a specific gated action, including the time window for which the allowance applies, the total allowance, and the amount used.

type AppRegistryClient

type AppRegistryClient interface {
	ApproveToken(amount decimal.Decimal) (string, error)
	GetBalance(user string) (decimal.Decimal, error)
	GetTokenDecimals() (uint8, error)

	Lock(targetWallet string, amount decimal.Decimal) (string, error)
	Relock() (string, error)
	Unlock() (string, error)
	Withdraw(destinationWallet string) (string, error)
}

type Asset

type Asset struct {
	Name                  string  `json:"name"`                    // Asset name
	Decimals              uint8   `json:"decimals"`                // Number of decimal places at YN
	Symbol                string  `json:"symbol"`                  // Asset symbol
	SuggestedBlockchainID uint64  `json:"suggested_blockchain_id"` // Suggested blockchain network ID for this asset
	Tokens                []Token `json:"tokens"`                  // Supported tokens for the asset
}

Asset represents information about a supported asset

type AssetStore

type AssetStore interface {
	// GetAssetDecimals checks if an asset exists and returns its decimals in YN
	GetAssetDecimals(asset string) (uint8, error)

	// GetTokenDecimals returns the decimals for a token on a specific blockchain
	GetTokenDecimals(blockchainID uint64, tokenAddress string) (uint8, error)
}

type BalanceEntry

type BalanceEntry struct {
	Asset   string          `json:"asset"`   // Asset symbol
	Balance decimal.Decimal `json:"balance"` // Balance amount
}

BalanceEntry represents a balance entry for an asset

type Blockchain

type Blockchain struct {
	Name                   string `json:"name"`                     // Blockchain name
	ID                     uint64 `json:"id"`                       // Blockchain network ID
	ChannelHubAddress      string `json:"channel_hub_address"`      // Address of the ChannelHub contract on this blockchain
	LockingContractAddress string `json:"locking_contract_address"` // Address of the Locking contract on this blockchain
	BlockStep              uint64 `json:"block_step"`               // Number of blocks between each channel update
}

Blockchain represents information about a supported blockchain network

type BlockchainClient

type BlockchainClient interface {
	// Getters - IVault
	GetAccountsBalances(accounts []string, tokens []string) ([][]decimal.Decimal, error)

	// Getters - Token Balance & Approval
	GetTokenBalance(asset string, walletAddress string) (decimal.Decimal, error)
	Approve(asset string, amount decimal.Decimal) (string, error)

	// Getters - ChannelsHub
	GetNodeBalance(token string) (decimal.Decimal, error)
	GetOpenChannels(user string) ([]string, error)
	GetHomeChannelData(homeChannelID string) (HomeChannelDataResponse, error)
	GetEscrowDepositData(escrowChannelID string) (EscrowDepositDataResponse, error)
	GetEscrowWithdrawalData(escrowChannelID string) (EscrowWithdrawalDataResponse, error)

	// IVault functions
	Deposit(node, token string, amount decimal.Decimal) (string, error)
	Withdraw(node, token string, amount decimal.Decimal) (string, error)

	// Node lifecycle
	EnsureSigValidatorRegistered(validatorID uint8, validatorAddress string, checkOnly bool) error

	// Channel lifecycle
	Create(def ChannelDefinition, initCCS State) (string, error)
	MigrateChannelHere(def ChannelDefinition, candidate State) (string, error)
	Checkpoint(candidate State) (string, error)
	Challenge(candidate State, challengerSig []byte, challengerIdx ChannelParticipant) (string, error)
	Close(candidate State) (string, error)

	// Escrow deposit
	InitiateEscrowDeposit(def ChannelDefinition, initCCS State) (string, error)
	ChallengeEscrowDeposit(candidate State, challengerSig []byte, challengerIdx ChannelParticipant) (string, error)
	FinalizeEscrowDeposit(candidate State) (string, error)

	// Escrow withdrawal
	InitiateEscrowWithdrawal(def ChannelDefinition, initCCS State) (string, error)
	ChallengeEscrowWithdrawal(candidate State, challengerSig []byte, challengerIdx ChannelParticipant) (string, error)
	FinalizeEscrowWithdrawal(candidate State) (string, error)
}

Client defines the interface for interacting with the ChannelsHub smart contract TODO: add context to all methods

type BlockchainEvent

type BlockchainEvent struct {
	ContractAddress string `json:"contract_address"`
	BlockchainID    uint64 `json:"blockchain_id"`
	Name            string `json:"name"`
	BlockNumber     uint64 `json:"block_number"`
	TransactionHash string `json:"transaction_hash"`
	LogIndex        uint32 `json:"log_index"`
}

type Channel

type Channel struct {
	ChannelID             string        `json:"channel_id"`                     // Unique identifier for the channel
	UserWallet            string        `json:"user_wallet"`                    // User wallet address
	Asset                 string        `json:"asset"`                          // Asset symbol (e.g. USDC, ETH)
	Type                  ChannelType   `json:"type"`                           // Type of the channel (home, escrow)
	BlockchainID          uint64        `json:"blockchain_id"`                  // Unique identifier for the blockchain
	TokenAddress          string        `json:"token_address"`                  // Address of the token used in the channel
	ChallengeDuration     uint32        `json:"challenge_duration"`             // Challenge period for the channel in seconds
	ChallengeExpiresAt    *time.Time    `json:"challenge_expires_at,omitempty"` // Timestamp when the challenge period elapses
	Nonce                 uint64        `json:"nonce"`                          // Nonce for the channel
	ApprovedSigValidators string        `json:"approved_sig_validators"`        // Bitmask representing approved signature validators for the channel
	Status                ChannelStatus `json:"status"`                         // Current status of the channel (void, open, challenged, closed)
	StateVersion          uint64        `json:"state_version"`                  // On-chain state version of the channel
}

Channel represents an on-chain channel

func NewChannel

func NewChannel(channelID, userWallet, asset string, ChType ChannelType, blockchainID uint64, tokenAddress string, nonce uint64, challenge uint32, approvedSigValidators string) *Channel

type ChannelDefaultSigner

type ChannelDefaultSigner struct {
	sign.Signer
}

func NewChannelDefaultSigner

func NewChannelDefaultSigner(signer sign.Signer) (*ChannelDefaultSigner, error)

func (*ChannelDefaultSigner) Sign

func (s *ChannelDefaultSigner) Sign(data []byte) (sign.Signature, error)

func (*ChannelDefaultSigner) Type

type ChannelDefinition

type ChannelDefinition struct {
	Nonce                 uint64 `json:"nonce"`                   // A unique number to prevent replay attacks
	Challenge             uint32 `json:"challenge"`               // Challenge period for the channel in seconds
	ApprovedSigValidators string `json:"approved_sig_validators"` // Bitmask representing approved signature validators for the channel
}

ChannelDefinition represents configuration for creating a channel

type ChannelHubEventHandler

type ChannelHubEventHandler interface {
	HandleHomeChannelCreated(context.Context, *HomeChannelCreatedEvent) error
	HandleHomeChannelMigrated(context.Context, *HomeChannelMigratedEvent) error
	HandleHomeChannelCheckpointed(context.Context, *HomeChannelCheckpointedEvent) error
	HandleHomeChannelChallenged(context.Context, *HomeChannelChallengedEvent) error
	HandleHomeChannelClosed(context.Context, *HomeChannelClosedEvent) error
	HandleEscrowDepositInitiated(context.Context, *EscrowDepositInitiatedEvent) error
	HandleEscrowDepositChallenged(context.Context, *EscrowDepositChallengedEvent) error
	HandleEscrowDepositFinalized(context.Context, *EscrowDepositFinalizedEvent) error
	HandleEscrowWithdrawalInitiated(context.Context, *EscrowWithdrawalInitiatedEvent) error
	HandleEscrowWithdrawalChallenged(context.Context, *EscrowWithdrawalChallengedEvent) error
	HandleEscrowWithdrawalFinalized(context.Context, *EscrowWithdrawalFinalizedEvent) error
}

Channel lifecycle event handlers

type ChannelParticipant

type ChannelParticipant uint8
var (
	ChannelParticipantUser ChannelParticipant = 0
	ChannelParticipantNode ChannelParticipant = 1
)

type ChannelSessionKeySignerV1

type ChannelSessionKeySignerV1 struct {
	sign.Signer
	// contains filtered or unexported fields
}

func NewChannelSessionKeySignerV1

func NewChannelSessionKeySignerV1(signer sign.Signer, metadataHash, authSig string) (*ChannelSessionKeySignerV1, error)

func (*ChannelSessionKeySignerV1) Sign

func (s *ChannelSessionKeySignerV1) Sign(data []byte) (sign.Signature, error)

func (*ChannelSessionKeySignerV1) Type

type ChannelSessionKeyStateV1

type ChannelSessionKeyStateV1 struct {
	// ID Hash(user_address + session_key + version)
	UserAddress string    `json:"user_address"` // UserAddress is the user wallet address
	SessionKey  string    `json:"session_key"`  // SessionKey is the session key address for delegation
	Version     uint64    `json:"version"`      // Version is the version of the session key format
	Assets      []string  `json:"assets"`       // Assets associated with this session key
	ExpiresAt   time.Time `json:"expires_at"`   // Expiration time as unix timestamp of this session key
	UserSig     string    `json:"user_sig"`     // UserSig is the user's signature over the session key metadata to authorize the registration/update of the session key
}

ChannelSessionKeyStateV1 represents the state of a session key.

type ChannelSigValidator

type ChannelSigValidator struct {
	// contains filtered or unexported fields
}

func NewChannelSigValidator

func NewChannelSigValidator(permissionsVerifier VerifyChannelSessionKePermissionsV1) *ChannelSigValidator

func (*ChannelSigValidator) Recover

func (s *ChannelSigValidator) Recover(data, sig []byte) (string, error)

func (*ChannelSigValidator) Verify

func (s *ChannelSigValidator) Verify(wallet string, data, sig []byte) error

type ChannelSigner

type ChannelSigner interface {
	sign.Signer
	Type() ChannelSignerType
}

type ChannelSignerType

type ChannelSignerType uint8
const (
	ChannelSignerType_Default    ChannelSignerType = 0x00
	ChannelSignerType_SessionKey ChannelSignerType = 0x01
)

func GetSignerType

func GetSignerType(sig []byte) (ChannelSignerType, error)

func (ChannelSignerType) String

func (t ChannelSignerType) String() string

type ChannelStatus

type ChannelStatus uint8
var (
	ChannelStatusVoid       ChannelStatus = 0
	ChannelStatusOpen       ChannelStatus = 1
	ChannelStatusChallenged ChannelStatus = 2
	ChannelStatusClosed     ChannelStatus = 3
)

func (*ChannelStatus) Scan

func (s *ChannelStatus) Scan(src any) error

func (ChannelStatus) String

func (s ChannelStatus) String() string

type ChannelType

type ChannelType uint8
var (
	ChannelTypeHome   ChannelType = 1
	ChannelTypeEscrow ChannelType = 2
)

type EscrowDepositChallengedEvent

type EscrowDepositChallengedEvent channelChallengedEvent

EscrowDepositChallengedEvent represents the EscrowDepositChallenged event

type EscrowDepositDataResponse

type EscrowDepositDataResponse struct {
	EscrowChannelID string `json:"escrow_channel_id"`
	Node            string `json:"node"`
	LastState       State  `json:"last_state"`
	UnlockExpiry    uint64 `json:"unlock_expiry"`
	ChallengeExpiry uint64 `json:"challenge_expiry"`
}

EscrowDepositDataResponse represents the response from getEscrowDepositData

type EscrowDepositFinalizedEvent

type EscrowDepositFinalizedEvent channelEvent

EscrowDepositFinalizedEvent represents the EscrowDepositFinalized event

type EscrowDepositInitiatedEvent

type EscrowDepositInitiatedEvent channelEvent

EscrowDepositInitiatedEvent represents the EscrowDepositInitiated event

type EscrowWithdrawalChallengedEvent

type EscrowWithdrawalChallengedEvent channelChallengedEvent

EscrowWithdrawalChallengedEvent represents the EscrowWithdrawalChallenged event

type EscrowWithdrawalDataResponse

type EscrowWithdrawalDataResponse struct {
	EscrowChannelID string `json:"escrow_channel_id"`
	Node            string `json:"node"`
	LastState       State  `json:"last_state"`
}

EscrowWithdrawalDataResponse represents the response from getEscrowWithdrawalData

type EscrowWithdrawalFinalizedEvent

type EscrowWithdrawalFinalizedEvent channelEvent

EscrowWithdrawalFinalizedEvent represents the EscrowWithdrawalFinalized event

type EscrowWithdrawalInitiatedEvent

type EscrowWithdrawalInitiatedEvent channelEvent

EscrowWithdrawalInitiatedEvent represents the EscrowWithdrawalInitiated event

type GatedAction

type GatedAction string

GatedAction represents an action that can be gated behind certain conditions, such as feature flags or access controls.

var (
	GatedActionTransfer GatedAction = "transfer"

	GatedActionAppSessionCreation   GatedAction = "app_session_creation"
	GatedActionAppSessionOperation  GatedAction = "app_session_operation"
	GatedActionAppSessionDeposit    GatedAction = "app_session_deposit"
	GatedActionAppSessionWithdrawal GatedAction = "app_session_withdrawal"
)

func GatedActionFromID

func GatedActionFromID(id uint8) (GatedAction, bool)

GatedActionFromID returns the GatedAction corresponding to the given uint8 ID. Returns an empty GatedAction and false if the ID is unknown.

func (GatedAction) ID

func (g GatedAction) ID() uint8

ID returns a unique identifier for the GatedAction, which can be used for efficient storage and retrieval in databases or feature flag systems.

type HomeChannelChallengedEvent

type HomeChannelChallengedEvent channelChallengedEvent

HomeChannelChallengedEvent represents the Challenged event

type HomeChannelCheckpointedEvent

type HomeChannelCheckpointedEvent channelEvent

HomeChannelCheckpointedEvent represents the Checkpointed event

type HomeChannelClosedEvent

type HomeChannelClosedEvent channelEvent

HomeChannelClosedEvent represents the Closed event

type HomeChannelCreatedEvent

type HomeChannelCreatedEvent channelEvent

HomeChannelCreatedEvent represents the ChannelCreated event

type HomeChannelDataResponse

type HomeChannelDataResponse struct {
	Definition      ChannelDefinition `json:"definition"`
	Node            string            `json:"node"`
	LastState       State             `json:"last_state"`
	ChallengeExpiry uint64            `json:"challenge_expiry"`
}

HomeChannelDataResponse represents the response from getHomeChannelData

type HomeChannelMigratedEvent

type HomeChannelMigratedEvent channelEvent

HomeChannelMigratedEvent represents the ChannelMigrated event

type Ledger

type Ledger struct {
	TokenAddress string          `json:"token_address"` // Address of the token used in this channel
	BlockchainID uint64          `json:"blockchain_id"` // Unique identifier for the blockchain
	UserBalance  decimal.Decimal `json:"user_balance"`  // User balance in the channel
	UserNetFlow  decimal.Decimal `json:"user_net_flow"` // User net flow in the channel
	NodeBalance  decimal.Decimal `json:"node_balance"`  // Node balance in the channel
	NodeNetFlow  decimal.Decimal `json:"node_net_flow"` // Node net flow in the channel
}

Ledger represents ledger balances

func (Ledger) Equal

func (l1 Ledger) Equal(l2 Ledger) error

func (Ledger) Validate

func (l Ledger) Validate() error

type LockingContractEventHandler

type LockingContractEventHandler interface {
	HandleUserLockedBalanceUpdated(context.Context, *UserLockedBalanceUpdatedEvent) error
}

type NodeConfig

type NodeConfig struct {
	// NodeAddress is the Ethereum address of the clearnode operator
	NodeAddress string

	// NodeVersion is the software version of the clearnode instance
	NodeVersion string

	// SupportedSigValidators is the list of supported signature validator types
	SupportedSigValidators []ChannelSignerType

	// Blockchains is the list of supported blockchain networks
	Blockchains []Blockchain
}

NodeConfig represents the configuration of a Clearnode instance. It includes the node's identity, version, and supported blockchain networks.

type PaginationMetadata

type PaginationMetadata struct {
	Page       uint32 `json:"page"`        // Current page number
	PerPage    uint32 `json:"per_page"`    // Number of items per page
	TotalCount uint32 `json:"total_count"` // Total number of items
	PageCount  uint32 `json:"page_count"`  // Total number of pages
}

PaginationMetadata contains pagination information for list responses.

type PaginationParams

type PaginationParams struct {
	Offset *uint32
	Limit  *uint32
	Sort   *string
}

PaginationParams provides pagination configuration for getters

func (*PaginationParams) GetOffsetAndLimit

func (p *PaginationParams) GetOffsetAndLimit(defaultLimit, maxLimit uint32) (offset, limit uint32)

GetOffsetAndLimit extracts offset and limit from pagination params with defaults and max limit enforcement.

type State

type State struct {
	ID              string     `json:"id"`                          // Deterministic ID (hash) of the state
	Transition      Transition `json:"transition"`                  // The transition that led to this state
	Asset           string     `json:"asset"`                       // Asset type of the state
	UserWallet      string     `json:"user_wallet"`                 // User wallet address
	Epoch           uint64     `json:"epoch"`                       // User Epoch Index
	Version         uint64     `json:"version"`                     // Version of the state
	HomeChannelID   *string    `json:"home_channel_id,omitempty"`   // Identifier for the home Channel ID
	EscrowChannelID *string    `json:"escrow_channel_id,omitempty"` // Identifier for the escrow Channel ID
	HomeLedger      Ledger     `json:"home_ledger"`                 // User and node balances for the home channel
	EscrowLedger    *Ledger    `json:"escrow_ledger,omitempty"`     // User and node balances for the escrow channel
	UserSig         *string    `json:"user_sig,omitempty"`          // User signature for the state
	NodeSig         *string    `json:"node_sig,omitempty"`          // Node signature for the state
}

State represents the current state of the user stored on Node

func NewVoidState

func NewVoidState(asset, userWallet string) *State

func (*State) ApplyAcknowledgementTransition

func (state *State) ApplyAcknowledgementTransition() (Transition, error)

func (*State) ApplyChannelCreation

func (state *State) ApplyChannelCreation(channelDef ChannelDefinition, blockchainID uint64, tokenAddress, nodeAddress string) (string, error)

ApplyChannelCreation applies channel creation parameters to the state and returns the calculated home channel ID.

func (*State) ApplyCommitTransition

func (state *State) ApplyCommitTransition(accountID string, amount decimal.Decimal) (Transition, error)

func (*State) ApplyEscrowDepositTransition

func (state *State) ApplyEscrowDepositTransition(amount decimal.Decimal) (Transition, error)

func (*State) ApplyEscrowLockTransition

func (state *State) ApplyEscrowLockTransition(blockchainID uint64, tokenAddress string, amount decimal.Decimal) (Transition, error)

func (*State) ApplyEscrowWithdrawTransition

func (state *State) ApplyEscrowWithdrawTransition(amount decimal.Decimal) (Transition, error)

func (*State) ApplyFinalizeTransition

func (state *State) ApplyFinalizeTransition() (Transition, error)

func (*State) ApplyHomeDepositTransition

func (state *State) ApplyHomeDepositTransition(amount decimal.Decimal) (Transition, error)

func (*State) ApplyHomeWithdrawalTransition

func (state *State) ApplyHomeWithdrawalTransition(amount decimal.Decimal) (Transition, error)

func (*State) ApplyMigrateTransition

func (state *State) ApplyMigrateTransition(amount decimal.Decimal) (Transition, error)

func (*State) ApplyMutualLockTransition

func (state *State) ApplyMutualLockTransition(blockchainID uint64, tokenAddress string, amount decimal.Decimal) (Transition, error)

func (*State) ApplyReleaseTransition

func (state *State) ApplyReleaseTransition(accountID string, amount decimal.Decimal) (Transition, error)

func (*State) ApplyTransferReceiveTransition

func (state *State) ApplyTransferReceiveTransition(sender string, amount decimal.Decimal, txID string) (Transition, error)

func (*State) ApplyTransferSendTransition

func (state *State) ApplyTransferSendTransition(recipient string, amount decimal.Decimal) (Transition, error)

func (*State) IsFinal

func (state *State) IsFinal() bool

func (State) NextState

func (state State) NextState() *State

type StateAdvancer

type StateAdvancer interface {
	ValidateAdvancement(currentState, proposedState State) error
}

StateAdvancer applies state transitions

type StateAdvancerV1

type StateAdvancerV1 struct {
	// contains filtered or unexported fields
}

StateAdvancerV1 provides basic validation for state transitions

func NewStateAdvancerV1

func NewStateAdvancerV1(assetStore AssetStore) *StateAdvancerV1

NewStateAdvancerV1 creates a new simple transition validator

func (*StateAdvancerV1) ValidateAdvancement

func (v *StateAdvancerV1) ValidateAdvancement(currentState, proposedState State) error

ValidateAdvancement validates that the proposed state is a valid advancement of the current state

type StatePacker

type StatePacker interface {
	PackState(state State) ([]byte, error)
}

StatePacker serializes channel states

type StatePackerV1

type StatePackerV1 struct {
	// contains filtered or unexported fields
}

func NewStatePackerV1

func NewStatePackerV1(assetStore AssetStore) *StatePackerV1

func (*StatePackerV1) PackChallengeState

func (p *StatePackerV1) PackChallengeState(state State) ([]byte, error)

PackChallengeState encodes a state for challenge signature verification. This matches the Solidity contract's challenge validation:

challengerSigningData = abi.encodePacked(abi.encode(version, intent, metadata, homeLedger, nonHomeLedger), "challenge")
message = abi.encode(channelId, challengerSigningData)

func (*StatePackerV1) PackState

func (p *StatePackerV1) PackState(state State) ([]byte, error)

PackState encodes a channel ID and state into ABI-packed bytes for on-chain submission. This matches the Solidity contract's two-step encoding:

Step 1: signingData = abi.encode(version, intent, metadata, homeLedger, nonHomeLedger)
Step 2: message = abi.encode(channelId, signingData)

type Token

type Token struct {
	Name         string `json:"name"`          // Token name
	Symbol       string `json:"symbol"`        // Token symbol
	Address      string `json:"address"`       // Token contract address
	BlockchainID uint64 `json:"blockchain_id"` // Blockchain network ID
	Decimals     uint8  `json:"decimals"`      // Number of decimal places
}

Token represents information about a supported token

type Transaction

type Transaction struct {
	ID                 string          `json:"id"`                              // Unique transaction reference
	Asset              string          `json:"asset"`                           // Asset symbol
	TxType             TransactionType `json:"tx_type"`                         // Transaction type
	FromAccount        string          `json:"from_account"`                    // The account that sent the funds
	ToAccount          string          `json:"to_account"`                      // The account that received the funds
	SenderNewStateID   *string         `json:"sender_new_state_id,omitempty"`   // The ID of the new sender's channel state
	ReceiverNewStateID *string         `json:"receiver_new_state_id,omitempty"` // The ID of the new receiver's channel state
	Amount             decimal.Decimal `json:"amount"`                          // Transaction amount
	CreatedAt          time.Time       `json:"created_at"`                      // When the transaction was created
}

Transaction represents a transaction record

func NewTransaction

func NewTransaction(id, asset string, txType TransactionType, fromAccount, toAccount string, senderNewStateID, receiverNewStateID *string, amount decimal.Decimal) *Transaction

NewTransaction creates a new instance of Transaction

func NewTransactionFromTransition

func NewTransactionFromTransition(senderState *State, receiverState *State, transition Transition) (*Transaction, error)

NewTransactionFromTransition maps the transition type to the appropriate transaction type and returns a pointer to a Transaction.

type TransactionType

type TransactionType uint8

TransactionType represents the type of transaction

const (
	TransactionTypeHomeDeposit    TransactionType = 10
	TransactionTypeHomeWithdrawal TransactionType = 11

	TransactionTypeEscrowDeposit  TransactionType = 20
	TransactionTypeEscrowWithdraw TransactionType = 21

	TransactionTypeTransfer TransactionType = 30

	TransactionTypeCommit    TransactionType = 40
	TransactionTypeRelease   TransactionType = 41
	TransactionTypeRebalance TransactionType = 42

	TransactionTypeMigrate    TransactionType = 100
	TransactionTypeEscrowLock TransactionType = 110
	TransactionTypeMutualLock TransactionType = 120

	TransactionTypeFinalize = 200
)

func (TransactionType) String

func (t TransactionType) String() string

String returns the human-readable name of the transaction type

type Transition

type Transition struct {
	Type      TransitionType  `json:"type"`       // Type of state transition
	TxID      string          `json:"tx_id"`      // Transaction ID associated with the transition
	AccountID string          `json:"account_id"` // Account identifier (varies based on transition type)
	Amount    decimal.Decimal `json:"amount"`     // Amount involved in the transition
}

Transition represents a state transition

func NewTransition

func NewTransition(transitionType TransitionType, txID, accountID string, amount decimal.Decimal) *Transition

NewTransition creates a new state transition

func (Transition) Equal

func (t1 Transition) Equal(t2 Transition) error

Equal checks if two transitions are equal

type TransitionType

type TransitionType uint8

TransitionType represents the type of state transition

const (
	TransitionTypeVoid                           = 0 // Void transition, used for the initial state with no activity
	TransitionTypeAcknowledgement TransitionType = 1 // Acknowledgement of a received transfer, used for the initial state when a transfer is received without an existing state

	TransitionTypeHomeDeposit    TransitionType = 10 // AccountID: HomeChannelID
	TransitionTypeHomeWithdrawal TransitionType = 11 // AccountID: HomeChannelID

	TransitionTypeEscrowDeposit  TransitionType = 20 // AccountID: EscrowChannelID
	TransitionTypeEscrowWithdraw TransitionType = 21 // AccountID: EscrowChannelID

	TransitionTypeTransferSend    TransitionType = 30 // AccountID: Receiver's UserWallet
	TransitionTypeTransferReceive TransitionType = 31 // AccountID: Sender's UserWallet

	TransitionTypeCommit  TransitionType = 40 // AccountID: AppSessionID
	TransitionTypeRelease TransitionType = 41 // AccountID: AppSessionID

	TransitionTypeMigrate    TransitionType = 100 // AccountID: EscrowChannelID
	TransitionTypeEscrowLock TransitionType = 110 // AccountID: EscrowChannelID
	TransitionTypeMutualLock TransitionType = 120 // AccountID: EscrowChannelID

	TransitionTypeFinalize TransitionType = 200 // AccountID: HomeChannelID
)

func (TransitionType) GatedAction

func (t TransitionType) GatedAction() GatedAction

func (TransitionType) String

func (t TransitionType) String() string

String returns the human-readable name of the transition type

type UserLockedBalanceUpdatedEvent

type UserLockedBalanceUpdatedEvent struct {
	UserAddress  string          `json:"user_address"`
	BlockchainID uint64          `json:"blockchain_id"`
	Balance      decimal.Decimal `json:"balance"`
}

type VerifyChannelSessionKePermissionsV1

type VerifyChannelSessionKePermissionsV1 func(walletAddr, sessionKeyAddr, metadataHash string) (bool, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL