celersdk

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: May 2, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

this file defines externalsigner interface for app to implement and provides common.signer to cnode, also adds new API for create sdk client

Index

Constants

View Source
const SignTimeout = 60 * time.Second

wait at most 60s for external to return sign result

Variables

View Source
var (
	ErrNilExtSigner  = errors.New("external signer is nil")
	ErrResultTimeout = errors.New("timeout waiting for sign result")
	ErrInvalidReqID  = errors.New("invalid sign reqid")
	ErrNilResult     = errors.New("sign result is nil")
)

Functions

func GetCelerErrCode

func GetCelerErrCode(e error) int

GetCelerErrCode is the helper util to return errcode if e is a celersdkintf.E other wise returns -1. meaning -1 is reserved and shouldn't be used by other systems

func InitClient

func InitClient(acnt *Account, cfg, dataPath string, cb ClientCallback)

InitClient creates a celer client cfg is the content of profile json file. dataPath is the dir that holds celer data.

func InitClientWithSigner

func InitClientWithSigner(addr, cfg, dataPath string, cb ClientCallback, signcb ExternalSignerCallback)

InitClientWithSigner creates celer client with external signer addr is hex string of ETH address eg. 0x1234...

func PublishSignedResult

func PublishSignedResult(reqid int, result []byte) error

SDK API for mobile to call to send back sign result if mobile has error, send nil result so signer will know sign failed

func SetLogCallback

func SetLogCallback(cb LogCallback)

SetLogCallback set the self-defined writer in the log module. Once set, logs will be written to cb.Onlog() instead of os.Stderr

func Version

func Version() string

Version returns CelerSDK version

Types

type Account

type Account struct {
	Keystore string
	Password string
}

type AppBooleanOutcome

type AppBooleanOutcome struct {
	Finalized bool
	Outcome   bool
}

AppBooleanOutcome carries the result of an `IBooleanCond` query: whether the outcome has been finalized, and the boolean outcome itself.

type AppSession

type AppSession struct {
	ID string
	// contains filtered or unexported fields
}

func (*AppSession) GetDeployedAddress

func (s *AppSession) GetDeployedAddress() (string, error)

GetDeployedAddress returns the on-chain deployed address of the registered virtual condition contract. Returns an error if the contract has not been deployed yet (deployment is triggered lazily by `OnChainGetBooleanOutcome`).

func (*AppSession) OnChainGetBooleanOutcome

func (s *AppSession) OnChainGetBooleanOutcome(query []byte) (*AppBooleanOutcome, error)

OnChainGetBooleanOutcome queries `IBooleanCond.{isFinalized,getOutcome}` on the registered condition contract. For VIRTUAL_CONTRACT this triggers deploy-on-query: if the virtual contract has not been deployed yet, this call submits a deployment transaction first.

type Balance

type Balance struct {
	Available    string
	Pending      string
	ReceivingCap string
}

offchain balance struct

type BooleanCondition

type BooleanCondition struct {
	OnChainDeployed        bool
	OnChainAddress         string // on-chain IBooleanCond contract address if OnChainDeployed is true
	VirtualContractAddress string // deterministic virtual-contract address (hex) from CreateAppSessionOnVirtualContract; ignored if OnChainDeployed is true
	ArgsForQueryOutcome    []byte
	TimeoutSec             int // pay deadline = wall-clock unix time + TimeoutSec
}

type CSharedRandom

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

func NewSharedRandom

func NewSharedRandom(matchID string) *CSharedRandom

func (*CSharedRandom) GetSharedRandom

func (sr *CSharedRandom) GetSharedRandom() float64

type CelerStatus

type CelerStatus struct {
	JoinStatus  int32
	FreeBalance string
}

CelerStatus defines a struct to store the join status and free balance of a celer endpoint For field JoinStatus, it has three values which are 0, 1 and 2. 0 means address queried does not join Celer Network. 1 means this address has a channel with Osp responsing this query(Local). 2 means this address has a channel with another Osp in Celer Network(Remote). For field FreeBalance, it uses a decimal string to represent the receiving capacity of address queried. When receiving this status, developers should first check JoinStatus, if it is not 1(Local), you should just ignore FreeBalance. Only when JoinStatus is 1 could the developer further use FreeBalance.

type Client

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

Celer mobile client. must define before methods! gobind has a bug to clear method doc if struct is defined after methods

func (*Client) ConfirmOnChainResolvedPays

func (mc *Client) ConfirmOnChainResolvedPays(tk *Token) error

ConfirmOnChainResolvedPays confirms pays that have been onchain resolved, if tk is nil, means ETH

func (*Client) ConfirmPay

func (mc *Client) ConfirmPay(payID string) error

ConfirmPay settles the condpay, ie. actually paid to pay dest

func (*Client) ConfirmSettlePaymentChannel

func (mc *Client) ConfirmSettlePaymentChannel(tokenInfo *TokenInfo) error

func (*Client) ConfirmWithdraw

func (mc *Client) ConfirmWithdraw(tokenInfo *TokenInfo) error

func (*Client) CreateAppSessionOnVirtualContract

func (mc *Client) CreateAppSessionOnVirtualContract(
	contractBin string,
	constructor string,
	nonce uint64) (*AppSession, error)

CreateAppSessionOnVirtualContract registers a VIRTUAL_CONTRACT condition contract on the cnode and returns an `AppSession` keyed by its deterministic virtual-contract address. The contract is deployed lazily on first outcome query (via `OnChainGetBooleanOutcome`).

func (*Client) DepositERC20

func (mc *Client) DepositERC20(
	token *Token, amount string, callback DepositCallback) (string, error)

func (*Client) DepositETH

func (mc *Client) DepositETH(amount string, callback DepositCallback) (string, error)

func (*Client) Destroy

func (mc *Client) Destroy()

Destroy tries best to do clean up of current client note after this returns, all API calls to same client will crash. This is by design to catch invalid call flow. So caller should be careful about the lifecycle management. There is no need to call Destroy if client isn't init correctly

func (*Client) EndAppSession

func (mc *Client) EndAppSession(sessionid string)

EndAppSession removes the registered virtual condition contract from the cnode's in-memory bookkeeping. The current implementation always succeeds; it cannot fail.

func (*Client) GetAllPayments

func (mc *Client) GetAllPayments() (*celersdkintf.PaymentList, error)

GetAllPayments returns all payments info. **CAUTION**: This function costs heavy lookup on several tables and joins information from those tables, please take performance into consideration before using this. PaymentList.PayList is list of all payments. But due to gomobile limitation (no return list). mobile app needs to do following payList = GetAllPayments()

for i=0; i<payList.Length; i++ {
    pay = payList.Get(i)
}

func (*Client) GetBalance

func (mc *Client) GetBalance() (*Balance, error)

Get celer offchain ETH balance

func (*Client) GetBalanceERC20

func (mc *Client) GetBalanceERC20(tokenAddr string) (*Balance, error)

GetBalanceERC20 gets celer offchain tokenAddr balance

func (*Client) GetChannelState

func (mc *Client) GetChannelState(tk *Token) string

GetChannelState returns a string for channel state for given token

func (*Client) GetCurrentBlockNumber

func (mc *Client) GetCurrentBlockNumber() int64

func (*Client) GetDataDir

func (mc *Client) GetDataDir() string

GetDataDir returns dataPath when InitClient, so cxc can share same folder

func (*Client) GetIncomingPaymentInfo added in v1.1.0

func (mc *Client) GetIncomingPaymentInfo(paymentID string) (*celersdkintf.Payment, error)

GetIncomingPaymentInfo returns the related payment info for an incoming payment ID. It returns ErrPayNotFound if the payment does not belong to this client as receiver.

func (*Client) GetIncomingPaymentStatus

func (mc *Client) GetIncomingPaymentStatus(payId string) int

Get incoming payment status code

func (*Client) GetOnChainPaymentInfo

func (mc *Client) GetOnChainPaymentInfo(paymentID string) (*OnChainPaymentInfo, error)

func (*Client) GetOutgoingPaymentStatus

func (mc *Client) GetOutgoingPaymentStatus(payId string) int

Get outgoing payment status code

func (*Client) GetPayHistoryIterator

func (mc *Client) GetPayHistoryIterator() (*PayHistoryIterator, error)

GetPayHistoryIterator returns a celer crypto pay history iterator. Caller can call "NextPage" to get paginated pay history.

func (*Client) GetPayment

func (mc *Client) GetPayment(paymentID string) (*celersdkintf.Payment, error)

GetPayment returns the related payment info of a specified payment ID

func (*Client) GetSettleFinalizedTimeForPaymentChannel

func (mc *Client) GetSettleFinalizedTimeForPaymentChannel(tokenInfo *TokenInfo) (int64, error)

func (*Client) HasPendingOpenChanRequest

func (mc *Client) HasPendingOpenChanRequest(tk *Token) bool

HasPendingOpenChanRequest is expected to be called when GetChannelState returns NOT_FOUND in this case, it's helpful to know whether client has a pending onchain open channel request so app can update UI and/or try open again. Note pending true is only possible for client iniated onchain openchannel, not TCB

Internally we save the unix timestamp (seconds) when an openchan request starts; if time.Now().Unix() <= saved+OpenChannelTimeout we return true. The value is set to 0 in the openchan callback so future calls return false.

func (*Client) InstantiateChannelForToken

func (mc *Client) InstantiateChannelForToken(tk *Token, cb ClientCallback)

func (*Client) IntendSettlePaymentChannel

func (mc *Client) IntendSettlePaymentChannel(tokenInfo *TokenInfo) error

func (*Client) IntendWithdraw

func (mc *Client) IntendWithdraw(tokenInfo *TokenInfo, amount string) error

func (*Client) MonitorCooperativeWithdrawJob

func (mc *Client) MonitorCooperativeWithdrawJob(
	withdrawHash string, callback CooperativeWithdrawCallback)

func (*Client) MonitorDepositJob

func (mc *Client) MonitorDepositJob(jobID string, callback DepositCallback)

func (*Client) OpenETHChannel

func (mc *Client) OpenETHChannel(dep *Deposit, cb ClientCallback)

func (*Client) OpenTokenChannel

func (mc *Client) OpenTokenChannel(tk *Token, dep *Deposit, cb ClientCallback)

TODO(erctype): use proper enum based on tk.Erctype string

func (*Client) QueryReceivingCapacity

func (mc *Client) QueryReceivingCapacity(addr string) (*CelerStatus, error)

QueryReceivingCapacity Check whether address has also joined Celer and returns its join status and free balance in a decimal string. It is useful for checking the state of the intended receiver. If the given address has not joined Celer, an empty string will be returned.

func (*Client) QueryReceivingCapacityOnToken

func (mc *Client) QueryReceivingCapacityOnToken(tokenAddr string, addr string) (*CelerStatus, error)

QueryReceivingCapacityOnToken Check whether address has also joined Celer on tokenAddr and returns its join status and free balance in a decimal string. It is useful for checking the state of the intended receiver. If the given address has not joined Celer, an empty string will be returned.

func (*Client) RejectPay

func (mc *Client) RejectPay(payID string) error

RejectPay cancels the pay, ie. ask OSP and pay src to not pay

func (*Client) RemoveCooperativeWithdrawJob

func (mc *Client) RemoveCooperativeWithdrawJob(withdrawHash string)

func (*Client) RemoveDepositJob

func (mc *Client) RemoveDepositJob(jobID string)

func (*Client) RemoveExpiredPays

func (mc *Client) RemoveExpiredPays(tk *Token) error

RemoveExpiredPays clears pending pays that have expired, if tk is nil, means ETH

func (*Client) ResolveIncomingPaymentOnChain

func (mc *Client) ResolveIncomingPaymentOnChain(payId string) error

ResolveIncomingPaymentOnChain submits PayResolver.resolvePaymentByConditions for the given payment. See ResolvePayOnChain doc for the VIRTUAL_CONTRACT deploy-before-resolve prerequisite — the same applies here.

func (*Client) ResolvePayOnChain

func (mc *Client) ResolvePayOnChain(payID string) error

ResolvePayOnChain settles the payment onchain and receives the payment from OSP.

VIRTUAL_CONTRACT prerequisite: PayResolver.resolvePaymentByConditions calls VirtContractResolver.resolve(virtAddr) on-chain, which reverts with "Nonexistent virtual address" if the virtual condition contract has not been deployed yet. The surviving deploy path is the deploy-on-query side effect of AppSession.OnChainGetBooleanOutcome — calling it once after registration (e.g. with a no-op query) ensures the virtual contract has bytecode by the time this resolve tx lands. DEPLOYED_CONTRACT conditions have no such prerequisite.

func (*Client) SendConditionalPayment

func (mc *Client) SendConditionalPayment(
	tokenInfo *TokenInfo,
	destination string,
	amount string,
	transferLogicType TransferLogicType,
	conditions []*Condition,
	timeout int64,
	note *anypb.Any) (string, error)

func (*Client) SendETH

func (mc *Client) SendETH(receiver string, amtWei string, noteTypeUrl string, noteValueByte []byte) (string, error)

noteTypeUrl should be type url of any.Any. noteStr should be string representation of []byte in note (any.Any)

func (*Client) SendETHWithCondition

func (mc *Client) SendETHWithCondition(receiver string, amtWei string, cond *BooleanCondition) (string, error)

func (*Client) SendToken

func (mc *Client) SendToken(tk *Token, receiver string, amtWei string, noteTypeUrl string, noteValueByte []byte) (string, error)

SendETH sends ERC20/ETH token to receiver. Caller can optionally add a note in the pay.

func (*Client) SendTokenWithCondition

func (mc *Client) SendTokenWithCondition(tk *Token, receiver string, amtWei string, cond *BooleanCondition) (string, error)

When should we call onSent? or do we need a new callback func?

func (*Client) SetDelegation

func (mc *Client) SetDelegation(tks []*Token, duration int64) error

func (*Client) SetMsgDropper

func (mc *Client) SetMsgDropper(dropRecv, dropSend bool)

SetMsgDropper will drop grpc msgs, used for testing only

func (*Client) SettleExpiredPayments

func (mc *Client) SettleExpiredPayments(tokenInfo *TokenInfo) error

func (*Client) SettleOnChainResolvedIncomingPayment

func (mc *Client) SettleOnChainResolvedIncomingPayment(payId string) error

func (*Client) SignData

func (mc *Client) SignData(data []byte) ([]byte, error)

SignData signs arbitrary data and returns the signature

func (*Client) SyncOnChainChannelStates

func (mc *Client) SyncOnChainChannelStates(tk *Token) error

func (*Client) TcbOpenETHChannel

func (mc *Client) TcbOpenETHChannel(peerAmtWei string, cb ClientCallback)

func (*Client) TcbOpenTokenChannel

func (mc *Client) TcbOpenTokenChannel(tk *Token, peerAmtWei string, cb ClientCallback)

func (*Client) WithdrawERC20

func (mc *Client) WithdrawERC20(
	token *Token, amount string, callback CooperativeWithdrawCallback) (string, error)

func (*Client) WithdrawETH

func (mc *Client) WithdrawETH(amount string, callback CooperativeWithdrawCallback) (string, error)

type ClientCallback

type ClientCallback interface {
	HandleClientReady(c *Client)
	HandleClientInitErr(e *celersdkintf.E)
	HandleChannelOpened(token, cid string)
	HandleOpenChannelError(token, reason string)
	// Callback triggered when secret revealed.
	HandleRecvStart(pay *celersdkintf.Payment)
	// Callback triggered when pay settle request processed.
	HandleRecvDone(pay *celersdkintf.Payment)
	HandleSendComplete(pay *celersdkintf.Payment)
	HandleSendErr(pay *celersdkintf.Payment, e *celersdkintf.E)
}

type Condition

type Condition struct {
	// Whether the condition is based on an on-chain deployed contract
	OnChainDeployed bool
	// On-chain contract address bytes if OnChainDeployed is true, or virtual contract address
	ContractAddress []byte
	// Args to isFinalized()
	IsFinalizedArgs []byte
	// Args to getOutcome()
	GetOutcomeArgs []byte
}

type CooperativeWithdrawCallback

type CooperativeWithdrawCallback interface {
	OnWithdraw(withdrawHash string, txHash string)
	OnError(withdrawHash string, err string)
}

type Deposit

type Deposit struct {
	Myamtwei   string
	Peeramtwei string
}

type DepositCallback

type DepositCallback interface {
	OnDeposit(jobID string, txHash string)
	OnError(jobID string, err string)
}

type ExternalSignerCallback

type ExternalSignerCallback interface {
	OnSignMessage(reqid int, msg []byte)
	// OnSignTransaction rawtx is RLP encoded bytes of Eth transaction
	OnSignTransaction(reqid int, rawtx []byte)
}

mobile needs to implement this as callback, corresponding cb will be called when need to sign stuff

type LogCallback

type LogCallback interface {
	// msg is the log output
	OnLog(msg string)
}

type OnChainPaymentInfo

type OnChainPaymentInfo struct {
	Amount          string
	ResolveDeadline uint64
}

type OnchainCallback

type OnchainCallback interface {
	OnSubmitted(uid string)
	OnMined(tx string)
	OnErr(e *celersdkintf.E)
}

type PayHistoryIterator

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

PayHistoryIterator is an iterator to get pay history.

func (*PayHistoryIterator) HasMoreResult

func (iter *PayHistoryIterator) HasMoreResult() bool

HasMoreResult returns false if the iterator has gone over all pays in history.

func (*PayHistoryIterator) NextPage

func (iter *PayHistoryIterator) NextPage(itemsPerPage int32) (string, error)

NextPage returns next (earlier) batch of pay history in JSON string and error. itemsPerPage specifies the max number of pays in the response. History entries returned in json encoding string and reverse-chronological order. If there is more to retrieve, hasMoreResult filed in iterator is set to true . Note that hasMoreResult could be true when #(entries left for retrival before calling the func) happens to be same as itemsPerPage. In this case, the next time calling NextPage will return empty history set and set hasMoreResult field in iterator to false.

type Token

type Token struct {
	Erctype string // ERC20, ERC721 etc.
	Addr    string // token contract addr
	Symbol  string // short name like gt, celr
}

type TokenInfo

type TokenInfo struct {
	TokenType    TokenType
	TokenAddress string
}

type TokenType

type TokenType int32

type TransferLogicType

type TransferLogicType int32

type UserInfo

type UserInfo struct {
	WalletAddr string
	EmailAddr  string
	Name       string
}

UserInfo defines user info to send fiat-related request

Jump to

Keyboard shortcuts

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