Skip to main content

Methods

This page provides a complete reference for all methods available in the NitroliteClient class from the @erc7824/nitrolite package.

Channel Lifecycle Methods

These methods are organized according to the typical lifecycle of a state channel.

1. Deposit Methods

The deposit phase includes methods for managing funds in the custody contract and handling token approvals.

deposit

Deposits tokens or ETH into the custody contract. Automatically handles ERC-20 approval if necessary. This is the first step in the channel lifecycle, as funds must be deposited before channels can be created. Funds deposited are held in a custody contract until they are allocated to channels or withdrawn.

Parameters

  • amount:bigint

Returns:Promise<Hash>

Example

await client.deposit(1_000_000_000_000_000_000n);
approveTokens

Manually approves the custody contract to spend the specified ERC-20 amount. While the deposit method handles approvals automatically, this method gives developers explicit control over token approvals. This is useful for implementing custom approval UX flows or for batching transactions with other operations.

Parameters

  • amount:bigint

Returns:Promise<Hash>

Example

await client.approveTokens(2_000_000n);
getTokenAllowance

Gets the current allowance granted to the custody contract for the specified ERC20 token. This is useful for implementing proper UX around approvals, checking if a user needs to approve tokens before depositing, or verifying if existing approvals are sufficient for planned operations.

Returns:Promise<bigint>

Example

const allowance = await client.getTokenAllowance();
getTokenBalance

Gets the on-chain balance of the specified ERC-20 token for the connected wallet address. This helps developers implement UX that shows users their available token balance before depositing, ensuring they have sufficient funds for the operation. It's particularly useful for validating input amounts in deposit forms.

Returns:Promise<bigint>

Example

const balance = await client.getTokenBalance();

2. Channel Creation Methods

createChannel

Creates a new state channel on-chain. This is a critical step in the Nitrolite workflow that establishes a secure payment channel between two participants. The method handles the complex process of constructing the initial state with proper allocations, signing it, and submitting the transaction to the custody contract. Developers use this to enable high-throughput, low-latency applications with instant payments between participants.

Parameters

Returns:Promise<{ channelId: ChannelId; initialState: State; txHash: Hash }>

Example

await client.createChannel({
initialAllocationAmounts: [700000n, 300000n], // [host amount, guest amount]
stateData: '0x1234' // Application-specific data
});
depositAndCreateChannel

Combines deposit and channel creation into a single operation, optimizing the user experience by reducing the steps required. This is ideal for applications where users start from scratch without existing deposits. It handles the entire initialization flow: token approval (if needed), depositing funds to the custody contract, and creating the channel. This creates a smoother onboarding process for users who want to start using your application immediately.

Parameters

Returns:Promise<{ channelId: ChannelId; initialState: State; depositTxHash: Hash; createChannelTxHash: Hash }>

Example

await client.depositAndCreateChannel(
1000000n, // Total amount to deposit
{
initialAllocationAmounts: [700000n, 300000n], // Initial channel allocation
stateData: '0x1234' // Application-specific data
}
);

3. Channel Operation Methods

checkpointChannel

Checkpoints a channel state on-chain, creating a permanent on-chain record of the latest state. This is essential for security and dispute resolution, as it provides an immutable record that both parties have agreed to the current channel state. Use this method periodically during long-running channels to minimize risk, before large allocation changes, or when a participant will be offline for extended periods.

Parameters

Returns:Promise<Hash>

Example

await client.checkpointChannel({
channelId, // The ID of the channel to checkpoint
candidateState // The latest state signed by both parties
});
challengeChannel

Initiates a challenge for a channel when the counterparty becomes unresponsive or refuses to cooperate. This is a dispute resolution mechanism that allows a participant to force progress in the channel by submitting their latest signed state. After challenge, the counterparty has a time window (challengeDuration) to respond with a later state, or the challenger's state will be considered final. This method protects users from losing funds due to counterparty unavailability.

Parameters

Returns:Promise<Hash>

Example

await client.challengeChannel({
channelId, // The ID of the channel to challenge
candidateState // The latest state you have that's signed by both parties
});
resizeChannel

Adjusts the total funds allocated to a channel using a new agreed state. This is crucial for dynamic applications where funding requirements change over time. Use this to add more funds to a channel that's running low (top-up), or to reduce the locked funds when less capacity is needed. Resizing requires consensus from both participants and results in an on-chain transaction that updates the channel's total capacity.

Parameters

Returns:Promise<Hash>

Example

await client.resizeChannel({
resizeState: {
channelId,
stateData: '0x5678',
allocations: newAllocations,
version: 2n,
intent: StateIntent.RESIZE,
serverSignature: signature
},
proofStates: []
});

4. Channel Closing Methods

closeChannel

Gracefully closes a channel on-chain using a mutually agreed final state. This is the standard way to end a channel when both participants are cooperative. The method submits the final state to the blockchain, which unlocks funds according to the agreed allocations and makes them available for withdrawal. This method should be your go-to approach for ending channels in normal circumstances, as it's gas-efficient and immediately settles the final balances.

Parameters

Returns:Promise<Hash>

Example

await client.closeChannel({
finalState: {
channelId, // The ID of the channel to close
stateData: '0x5678', // Application-specific data
allocations: [
{ destination: userAddress, token: tokenAddress, amount: 800000n },
{ destination: counterpartyAddress, token: tokenAddress, amount: 200000n }
],
version: 5n, // The latest state version number
serverSignature: signature // Counterparty's signature of this state
}
});

5. Withdrawal Methods

withdrawal

Withdraws tokens previously deposited into the custody contract back to the user's wallet. This allows users to reclaim their funds after channels have been closed. This method only affects available (unlocked) funds - it cannot withdraw tokens that are still locked in active channels. Use this as the final step in the channel lifecycle to complete the full deposit-use-withdraw flow and return funds to the user's control.

Parameters

  • amount:bigint

Returns:Promise<Hash>

Example

await client.withdrawal(500000n); // Withdraw 500,000 tokens

Account Information Methods

These methods provide information about your account's state:

getAccountChannels

Retrieves a list of all channel IDs associated with the connected account. This is essential for applications that need to monitor, display, or manage multiple channels simultaneously. Use this to build dashboards showing all user channels, to implement batch operations on multiple channels, or to verify channel existence before performing operations.

Returns:Promise<ChannelId[]>

Example

const channels = await client.getAccountChannels();
console.log(`User has ${channels.length} active channels`);
getAccountInfo

Provides a comprehensive view of the account's financial state within the Nitrolite system. Returns information about available (unlocked) funds, funds locked in active channels, and the total number of channels. This method is crucial for building UIs that show users their current balances and channel activity, for validating that sufficient funds are available before operations, and for monitoring the overall health of the user's Nitrolite account.

Returns:Promise<AccountInfo>

Example

const info = await client.getAccountInfo();
console.log(`Available: ${info.available}, Locked: ${info.locked}, Channels: ${info.channelCount}`);
Advanced Usage: Transaction Preparation

For Account Abstraction support and transaction preparation methods, see the Abstract Accounts page.

Example: Complete Channel Lifecycle

import { NitroliteClient } from '@erc7824/nitrolite';

// Initialize the client
const client = new NitroliteClient({
publicClient,
walletClient,
addresses: { custody, adjudicator, guestAddress, tokenAddress },
chainId: 137,
challengeDuration: 100n
});

// 1. Deposit funds
const depositTxHash = await client.deposit(1000000n);

// 2. Create a channel
const { channelId, initialState } = await client.createChannel({
initialAllocationAmounts: [700000n, 300000n],
stateData: '0x1234'
});

// 3. Get account info to verify funds are locked
const accountInfo = await client.getAccountInfo();
console.log(`Locked in channels: ${accountInfo.locked}`);

// 4. Later, resize the channel
const resizeTxHash = await client.resizeChannel({
resizeState: {
channelId,
stateData: '0x5678',
allocations: newAllocations,
version: 2n,
intent: StateIntent.RESIZE,
serverSignature: signature
},
proofStates: []
});

// 5. Close the channel
const closeTxHash = await client.closeChannel({
finalState: {
channelId,
stateData: '0x5678',
allocations: [
{ destination: userAddress, token: tokenAddress, amount: 800000n },
{ destination: counterpartyAddress, token: tokenAddress, amount: 200000n }
],
version: 5n,
serverSignature: signature
}
});

// 6. Withdraw funds
const withdrawTxHash = await client.withdrawal(800000n);