Channel

Example

await Channel.initialize({
url: 'ws://localhost:3001',
role: 'initiator'
initiatorId: 'ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH',
responderId: 'ak_V6an1xhec1xVaAhLuak7QoEbi6t7w5hEtYWp9bMKaJ19i6A9E',
initiatorAmount: 1e18,
responderAmount: 1e18,
pushAmount: 0,
channelReserve: 0,
ttl: 1000,
host: 'localhost',
port: 3002,
lockPeriod: 10,
async sign (tag, tx) => await account.signTransaction(tx)
})

Hierarchy

  • Channel

Constructors

Methods

  • Get balances

    The accounts param contains a list of addresses to fetch balances of. Those can be either account balances or a contract ones, encoded as an account addresses.

    If a certain account address had not being found in the state tree - it is simply skipped in the response.

    Example

    channel.balances([
    'ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH',
    'ak_V6an1xhec1xVaAhLuak7QoEbi6t7w5hEtYWp9bMKaJ19i6A9E'
    'ct_2dCUAWYZdrWfACz3a2faJeKVTVrfDYxCQHCqAt5zM15f3u2UfA'
    ]).then(balances =>
    console.log(balances['ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH'])
    )

    Parameters

    • accounts: `ak_${string}`[]

      List of addresses to fetch balances from

    Returns Promise<{ [key: AccountAddress]: string }>

  • Trigger call a contract update

    The call contract update is calling a preexisting contract inside the channel's internal state tree. The update is a change to be applied on top of the latest state.

    That would call a contract with the poster being the caller of it. Poster commits an amount of coins to the contract.

    The call would also create a call object inside the channel state tree. It contains the result of the contract call.

    It is worth mentioning that the gas is not consumed, because this is an off-chain contract call. It would be consumed if it were an on-chain one. This could happen if a call with a similar computation amount is to be forced on-chain.

    Example

    channel.callContract({
    contract: 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa',
    callData: 'cb_1111111111111111...',
    amount: 0,
    abiVersion: 1
    }).then(({ accepted, signedTx }) => {
    if (accepted) {
    console.log('Contract called succesfully')
    } else {
    console.log('Contract call has been rejected')
    }
    })

    Parameters

    Returns Promise<{ accepted: boolean; signedTx: `tx_${string}` }>

  • Call contract using dry-run

    In order to get the result of a potential contract call, one might need to dry-run a contract call. It takes the exact same arguments as a call would and returns the call object.

    The call is executed in the channel's state, but it does not impact the state whatsoever. It uses as an environment the latest channel's state and the current top of the blockchain as seen by the node.

    Example

    channel.callContractStatic({
    contract: 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa',
    callData: 'cb_1111111111111111...',
    amount: 0,
    abiVersion: 1
    }).then(({ returnValue, gasUsed }) => {
    console.log('Returned value:', returnValue)
    console.log('Gas used:', gasUsed)
    })

    Parameters

    • options: { abiVersion: number; amount: number; callData: `cb_${string}`; contract: `ct_${string}` }

      Options

      • abiVersion: number

        Version of the ABI

      • amount: number

        Amount the caller of the contract commits to it

      • callData: `cb_${string}`

        ABI encoded compiled AEVM call data for the code

      • contract: `ct_${string}`

        Address of the contract to call

    Returns Promise<CallContractOptions>

  • Clean up all locally stored contract calls

    Contract calls are kept locally in order for the participant to be able to look them up. They consume memory and in order for the participant to free it - one can prune all messages. This cleans up all locally stored contract calls and those will no longer be available for fetching and inspection.

    Returns Promise<void>

  • Trigger create contract update

    The create contract update is creating a contract inside the channel's internal state tree. The update is a change to be applied on top of the latest state.

    That would create a contract with the poster being the owner of it. Poster commits initially a deposit amount of coins to the new contract.

    Example

    channel.createContract({
    code: 'cb_HKtpipK4aCgYb17wZ...',
    callData: 'cb_1111111111111111...',
    deposit: 10,
    vmVersion: 3,
    abiVersion: 1
    }).then(({ accepted, signedTx, address }) => {
    if (accepted) {
    console.log('New contract has been created')
    console.log('Contract address:', address)
    } else {
    console.log('New contract has been rejected')
    }
    })

    Parameters

    • options: { abiVersion: number; callData: `cb_${string}`; code: `cb_${string}`; deposit: number | BigNumber; vmVersion: number }

      Options

      • abiVersion: number

        Version of the Application Binary Interface

      • callData: `cb_${string}`

        Api encoded compiled AEVM call data for the code

      • code: `cb_${string}`

        Api encoded compiled AEVM byte code

      • deposit: number | BigNumber

        Initial amount the owner of the contract commits to it

      • vmVersion: number

        Version of the Virtual Machine

    • sign: SignTx

      Function which verifies and signs create contract transaction

    Returns Promise<{ accepted: boolean; address: `ct_${string}`; signedTx: `tx_${string}` }>

  • Deposit coins into the channel

    After the channel had been opened any of the participants can initiate a deposit. The process closely resembles the update. The most notable difference is that the transaction has been co-signed: it is channel_deposit_tx and after the procedure is finished - it is being posted on-chain.

    Any of the participants can initiate a deposit. The only requirements are:

    • Channel is already opened
    • No off-chain update/deposit/withdrawal is currently being performed
    • Channel is not being closed or in a solo closing state
    • The deposit amount must be equal to or greater than zero, and cannot exceed the available balance on the channel (minus the channel_reserve)

    After the other party had signed the deposit transaction, the transaction is posted on-chain and onOnChainTx callback is called with on-chain transaction as first argument. After computing transaction hash it can be tracked on the chain: entering the mempool, block inclusion and a number of confirmations.

    After the minimum_depth block confirmations onOwnDepositLocked callback is called (without any arguments).

    When the other party had confirmed that the block height needed is reached onDepositLocked callback is called (without any arguments).

    Example

    channel.deposit(
    100,
    async (tx) => await account.signTransaction(tx),
    { onOnChainTx: (tx) => console.log('on_chain_tx', tx) }
    ).then(({ accepted, state }) => {
    if (accepted) {
    console.log('Deposit has been accepted')
    console.log('The new state is:', state)
    } else {
    console.log('Deposit has been rejected')
    }
    })

    Parameters

    • amount: number | BigNumber

      Amount of coins to deposit

    • sign: SignTx

      Function which verifies and signs deposit transaction

    • callbacks: Pick<ChannelState, "onOnChainTx" | "onOwnDepositLocked" | "onDepositLocked"> = {}

      Callbacks

    Returns Promise<{ accepted: boolean; state: ChannelState }>

  • Trigger a force progress contract call This call is going on-chain

    Example

    channel.forceProgress({
    contract: 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa',
    callData: 'cb_1111111111111111...',
    amount: 0,
    abiVersion: 1,
    gasPrice: 1000005554
    }).then(({ accepted, signedTx }) => {
    if (accepted) {
    console.log('Contract force progress call successful')
    } else {
    console.log('Contract force progress call has been rejected')
    }
    })

    Parameters

    • options: { abiVersion: number; amount: number; callData: `cb_${string}`; contract: `ct_${string}`; gasLimit?: number; gasPrice?: number }

      Options

      • abiVersion: number

        Version of the ABI

      • amount: number

        Amount the caller of the contract commits to it

      • callData: `cb_${string}`

        ABI encoded compiled AEVM call data for the code

      • contract: `ct_${string}`

        Address of the contract to call

      • Optional gasLimit?: number
      • Optional gasPrice?: number
    • sign: SignTx

      Function which verifies and signs contract force progress transaction

    • callbacks: Pick<ChannelState, "onOnChainTx"> = {}

      Callbacks

    Returns Promise<{ accepted: boolean; signedTx: `tx_${string}`; tx: Uint8Array | `tx_${string}` }>

  • Get contract call result

    The combination of a caller, contract and a round of execution determines the contract call. Providing an incorrect set of those results in an error response.

    Example

    channel.getContractCall({
    caller: 'ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH',
    contract: 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa',
    round: 3
    }).then(({ returnType, returnValue }) => {
    if (returnType === 'ok') console.log(returnValue)
    })

    Parameters

    • options: { caller: `ak_${string}`; contract: `ct_${string}`; round: number }

      Options

      • caller: `ak_${string}`

        Address of contract caller

      • contract: `ct_${string}`

        Address of the contract

      • round: number

        Round when contract was called

    Returns Promise<{ gasPrice: number | BigNumber; gasUsed: number | BigNumber; height: number; log: string; returnType: ContractCallReturnType; returnValue: string }>

  • Get the latest contract state

    Example

    channel.getContractState(
    'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa'
    ).then(({ contract }) => {
    console.log('deposit:', contract.deposit)
    })

    Parameters

    • contract: `ct_${string}`

      Address of the contract

    Returns Promise<{ contract: <internal>.Contract; contractState: object }>

  • Leave channel

    It is possible to leave a channel and then later reestablish the channel off-chain state and continue operation. When a leave method is called, the channel fsm passes it on to the peer fsm, reports the current mutually signed state and then terminates.

    The channel can be reestablished by instantiating another Channel instance with two extra params: existingChannelId and offchainTx (returned from leave method as channelId and signedTx respectively).

    Example

    channel.leave().then(({ channelId, signedTx }) => {
    console.log(channelId)
    console.log(signedTx)
    })

    Returns Promise<{ channelId: string; signedTx: `tx_${string}` }>

  • Register event listener function

    Possible events:

    • "error"
    • "onChainTx"
    • "ownWithdrawLocked"
    • "withdrawLocked"
    • "ownDepositLocked"
    • "depositLocked"

    TODO: the event list looks outdated

    Parameters

    • eventName: string

      Event name

    • callback: EventCallback

      Callback function

    Returns void

  • Get proof of inclusion

    If a certain address of an account or a contract is not found in the state tree - the response is an error.

    Example

    channel.poi({
    accounts: [
    'ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH',
    'ak_V6an1xhec1xVaAhLuak7QoEbi6t7w5hEtYWp9bMKaJ19i6A9E'
    ],
    contracts: ['ct_2dCUAWYZdrWfACz3a2faJeKVTVrfDYxCQHCqAt5zM15f3u2UfA']
    }).then(poi => console.log(poi))

    Parameters

    • addresses: { accounts: `ak_${string}`[]; contracts?: `ct_${string}`[] }

      Addresses

      • accounts: `ak_${string}`[]

        List of account addresses to include in poi

      • Optional contracts?: `ct_${string}`[]

        List of contract addresses to include in poi

    Returns Promise<`pi_${string}`>

  • Get current round

    If round cannot be determined (for example when channel has not been opened) it will return null.

    Returns null | number

  • Send generic message

    If message is an object it will be serialized into JSON string before sending.

    If there is ongoing update that has not yet been finished the message will be sent after that update is finalized.

    Example

    channel.sendMessage(
    'hello world',
    'ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH'
    )

    Parameters

    • message: string | object

      Message

    • recipient: `ak_${string}`

      Address of the recipient

    Returns Promise<void>

  • Trigger mutual close

    At any moment after the channel is opened, a closing procedure can be triggered. This can be done by either of the parties. The process is similar to the off-chain updates.

    Example

    channel.shutdown(
    async (tx) => await account.signTransaction(tx)
    ).then(tx => console.log('on_chain_tx', tx))

    Parameters

    • sign: Function

      Function which verifies and signs mutual close transaction

    Returns Promise<`tx_${string}`>

  • Trigger a transfer update

    The transfer update is moving coins from one channel account to another. The update is a change to be applied on top of the latest state.

    Sender and receiver are the channel parties. Both the initiator and responder can take those roles. Any public key outside the channel is considered invalid.

    Example

    channel.update(
    'ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH',
    'ak_V6an1xhec1xVaAhLuak7QoEbi6t7w5hEtYWp9bMKaJ19i6A9E',
    10,
    async (tx) => await account.signTransaction(tx)
    ).then(({ accepted, signedTx }) =>
    if (accepted) {
    console.log('Update has been accepted')
    }
    )

    Parameters

    • from: `ak_${string}`

      Sender's public address

    • to: `ak_${string}`

      Receiver's public address

    • amount: number | BigNumber

      Transaction amount

    • sign: SignTx

      Function which verifies and signs offchain transaction

    • metadata: string[] = []

      Metadata

    Returns Promise<{ accepted: boolean; errorCode?: number; errorMessage?: string; signedTx?: `tx_${string}` }>

  • Withdraw coins from the channel

    After the channel had been opened any of the participants can initiate a withdrawal. The process closely resembles the update. The most notable difference is that the transaction has been co-signed: it is channel_withdraw_tx and after the procedure is finished - it is being posted on-chain.

    Any of the participants can initiate a withdrawal. The only requirements are:

    • Channel is already opened
    • No off-chain update/deposit/withdrawal is currently being performed
    • Channel is not being closed or in a solo closing state
    • The withdrawal amount must be equal to or greater than zero, and cannot exceed the available balance on the channel (minus the channel_reserve)

    After the other party had signed the withdraw transaction, the transaction is posted on-chain and onOnChainTx callback is called with on-chain transaction as first argument. After computing transaction hash it can be tracked on the chain: entering the mempool, block inclusion and a number of confirmations.

    After the minimum_depth block confirmations onOwnWithdrawLocked callback is called (without any arguments).

    When the other party had confirmed that the block height needed is reached onWithdrawLocked callback is called (without any arguments).

    Example

    channel.withdraw(
    100,
    async (tx) => await account.signTransaction(tx),
    { onOnChainTx: (tx) => console.log('on_chain_tx', tx) }
    ).then(({ accepted, signedTx }) => {
    if (accepted) {
    console.log('Withdrawal has been accepted')
    } else {
    console.log('Withdrawal has been rejected')
    }
    })

    Parameters

    • amount: number | BigNumber

      Amount of coins to withdraw

    • sign: SignTx

      Function which verifies and signs withdraw transaction

    • callbacks: Pick<ChannelState, "onOnChainTx" | "onOwnWithdrawLocked" | "onWithdrawLocked"> = {}

      Callbacks

    Returns Promise<{ accepted: boolean; signedTx: `tx_${string}` }>

Generated using TypeDoc