Skip to main content

Query Methods & Notifications

Query methods retrieve information from a clearnode, while notifications provide real-time updates about state changes.


Overview

The Nitro RPC protocol provides two types of information retrieval:

Query Methods: Client-initiated requests to retrieve current state information (balances, channels, sessions, transactions).

Notifications: Server-initiated messages sent to all relevant active connections when events occur (balance changes, channel updates, incoming transfers).

Real-Time Updates

Combine query methods for initial state retrieval with notifications for ongoing monitoring. This pattern ensures your application always reflects the latest state without constant polling.


Query Methods Summary

MethodAuthenticationPurposePagination
get_configPublicRetrieve clearnode configurationNo
get_assetsPublicList supported assetsNo
get_app_definitionPublicFetch the definition for a specific app sessionNo
get_channelsPublicList payment channelsYes
get_app_sessionsPublicList app sessionsYes
get_ledger_balancesPrivateQuery current balancesNo
get_ledger_entriesPublicDetailed accounting entriesYes
get_ledger_transactionsPublicUser-facing transaction historyYes
get_rpc_historyPrivateFetch recent RPC invocationsYes
get_user_tagPrivateRetrieve user's alphanumeric tagNo
get_session_keysPrivateList active session keysYes
pingPublicConnection health checkNo
Authentication

Public methods can be called without authentication. Private methods require completing the authentication flow first.

Pagination defaults

Unless explicitly provided, paginated methods default to limit = 10 (maximum 100) and offset = 0, matching the broker’s ListOptions.


get_config

Name

get_config

Usage

Retrieves the clearnode's configuration: broker address plus supported blockchains and their custody/adjudicator contracts.

Request

No parameters.

Response

ParameterTypeDescriptionExample
broker_addressstringClearnode's wallet address"0xbbbb567890abcdef..."
networksarray<BlockchainInfo>List of supported blockchain networksSee structure below

BlockchainInfo Structure

FieldTypeDescriptionExample
chain_iduint32Network identifier137 (Polygon)
namestringHuman-readable blockchain name"Polygon"
custody_addressstringCustody contract address on this chain"0xCustodyContractAddress..."
adjudicator_addressstringAdjudicator contract address on this chain"0xAdjudicatorAddress..."

Use Cases:

  • Discover supported chains and contract addresses
  • Verify clearnode wallet address

get_assets

Name

get_assets

Usage

Retrieves all supported assets and their configurations across supported blockchains.

Request

ParameterTypeRequiredDescriptionExampleNotes
chain_iduint32NoFilter by specific chain137If omitted, returns assets for all chains

Response

ParameterTypeDescriptionExample
assetsarray<Asset>List of supported assetsSee structure below

Asset Structure

FieldTypeDescriptionExample
tokenstringToken contract address"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"
chain_iduint32Blockchain network identifier137
symbolstringToken symbol"usdc"
decimalsuint8Number of decimal places6

Use Cases:

  • Display supported assets in UI
  • Validate asset identifiers before transfers
  • Get contract addresses for specific chains

get_app_definition

Name

get_app_definition

Usage

Retrieves the immutable definition for a given app session so clients can verify governance parameters and participants.

Request

ParameterTypeRequiredDescriptionExample
app_session_idstringYesTarget app session identifier"0x9876543210fedcba..."

Response

Returns the AppDefinition structure:

FieldTypeDescription
protocolstringProtocol version ("NitroRPC/0.2" or "NitroRPC/0.4")
participantsarray<address>Wallet addresses authorized for this session
weightsarray<int64>Voting weight per participant (aligned with participants order)
quorumuint64Minimum combined weight required for updates
challengeuint64Dispute timeout (seconds)
nonceuint64Unique instance identifier

Use Cases:

  • Validate session metadata before signing states
  • Display governance rules in UI
  • Confirm protocol version compatibility

get_channels

Name

get_channels

Usage

Lists all channels for a specific participant address across all supported chains.

Request

ParameterTypeRequiredDescriptionDefaultExample
participantstringNoParticipant wallet address to query(empty = all channels)"0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb"
statusstringNoFilter by status-"open"
offsetnumberNoPagination offset042
limitnumberNoNumber of channels to return10 (max 100)10
sortstringNoSort order by created_at"desc""desc"

Allowed status values: "open" | "closed" | "challenged" | "resizing"

Response

ParameterTypeDescriptionExample
channelsarray<Channel>List of channelsSee structure below

Channel Structure

FieldTypeDescriptionExample
channel_idstringUnique channel identifier"0xabcdef..."
participantstringUser's wallet address"0x742d35Cc..."
statusstringChannel status"open"
tokenstringAsset contract address"0x2791Bca1..."
walletstringParticipant's wallet address"0x742d35Cc..."
amountstringTotal channel capacity (human-readable)"100.0"
chain_iduint32Blockchain network identifier137
adjudicatorstringDispute resolution contract address"0xAdjudicator..."
challengeuint64Dispute timeout period (seconds)3600
nonceuint64Unique nonce ensuring channel uniqueness1699123456789
versionuint64Current state version5
created_atstringChannel creation timestamp (ISO 8601)"2023-05-01T12:00:00Z"
updated_atstringLast modification timestamp (ISO 8601)"2023-05-01T14:30:00Z"

Use Cases:

  • Display user's open channels
  • Check channel status before operations
  • Monitor multi-chain channel distribution

get_app_sessions

Name

get_app_sessions

Usage

Lists all app sessions for a participant, sorted by creation date (newest first by default). Optionally filter by status (open/closed). Returns complete session information including participants, voting weights, quorum, protocol version, and current state. Supports pagination for large result sets.

Request

ParameterTypeRequiredDescriptionDefaultAllowed ValuesExample
participantstring (address)NoFilter by participant wallet address(empty = all sessions)"0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb"
statusstringNoFilter by status-"open"
offsetnumberNoPagination offset0-42
limitnumberNoNumber of sessions to return10 (max 100)-10
sortstringNoSort order by created_at"desc""desc"

Allowed status values: "open" | "closed"

Response

ParameterTypeDescriptionSee Also
app_sessionsarray<AppSessionInfo>List of app sessionsSee structure below

AppSessionInfo

FieldTypeDescriptionExample
app_session_idstringUnique identifier"0x9876543210fedcba..."
applicationstringApplication identifier"NitroliteChess"
statusstringCurrent status"open" | "closed"
participantsarray<address>All participant wallet addresses["0x742d35Cc...", "0x8B3192f2..."]
weightsarray<int64>Voting weights per participant[50, 50, 100]
quorumuint64Required weight for state updates100
protocolstringProtocol version"NitroRPC/0.4"
challengeuint64Challenge period in seconds86400
versionnumberCurrent state version5
nonceuint64Unique session identifier1699123456789
session_datastringCurrent application state"{\"gameType\":\"chess\",\"turn\":\"white\"}"
created_atstring (timestamp)Creation timestamp"2023-05-01T12:00:00Z"
updated_atstring (timestamp)Last update timestamp"2023-05-01T14:30:00Z"

Use Cases:

  • Display user's active games or escrows
  • Monitor session history
  • Paginate through large session lists
Pagination Best Practice

When dealing with users who have many app sessions, use pagination with reasonable limit values (10-50) to improve performance and user experience.


get_ledger_balances

Name

get_ledger_balances

Usage

Retrieves the ledger balances for an account. If no parameters are provided, returns the authenticated user's unified balance across all assets. Can also query balance within a specific app session by providing the app_session_id. Returns all tracked assets (including those that currently evaluate to zero).

Request

ParameterTypeRequiredDescriptionFormatExample
account_idstringNoAccount or app session identifier0x-prefixed hex string or wallet address"0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb"
App Session Balances

To query balance within a specific app session, provide the app_session_id as the account_id.

Response

ParameterTypeDescriptionExample
ledger_balancesarray<Balance>Balance per assetSee structure below

Balance Structure

FieldTypeDescriptionExample
assetstringAsset identifier"usdc"
amountstringBalance in human-readable format"100.0"

Use Cases:

  • Display user's current balances
  • Check available funds before operations
  • Monitor balance changes in real-time

get_ledger_entries

Name

get_ledger_entries

Usage

Retrieves detailed ledger entries for an account, providing a complete audit trail of all debits and credits. Each entry represents one side of a double-entry bookkeeping transaction. Used for detailed financial reconciliation and accounting. Supports filtering by account, asset, and pagination. Sorted by creation date (newest first by default).

Request

ParameterTypeRequiredDescriptionDefaultAllowed ValuesExample
account_idstringNoFilter by account identifier--"0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb"
walletstring (address)NoFilter by wallet address--"0x742d35Cc..."
assetstringNoFilter by asset--"usdc"
offsetnumberNoPagination offset0--
limitnumberNoNumber of entries to return10 (max 100)--
sortstringNoSort order by created_at"desc""asc" | "desc"-

Response

ParameterTypeDescriptionStructureExample
ledger_entriesarray<LedgerEntry>List of ledger entriesSee structure below

LedgerEntry Structure

FieldTypeDescriptionExample
idnumberUnique entry identifier123
account_idstringAccount this entry belongs to"0x742d35Cc..."
account_typenumberLedger account classification (1000=asset, 2000=liability, etc.)1000
assetstringAsset symbol"usdc"
participantstringParticipant wallet address"0x742d35Cc..."
creditstringCredit amount (incoming funds, "0.0" if debit)"100.0"
debitstringDebit amount (outgoing funds, "0.0" if credit)"25.0"
created_atstringEntry creation timestamp (ISO 8601)"2023-05-01T12:00:00Z"

Account types follow the broker’s GAAP-style codes: 1000 series for assets, 2000 liabilities, 3000 equity, 4000 revenue, and 5000 expenses.

Double-Entry Bookkeeping

Every transaction creates two entries:

Transfer: Alice sends 50 USDC to Bob

Entry 1 (Alice's ledger):
account_id: Alice's address
asset: usdc
credit: 0.0
debit: 50.0

Entry 2 (Bob's ledger):
account_id: Bob's address
asset: usdc
credit: 50.0
debit: 0.0
Accounting Principle

The double-entry system ensures that the total of all debits always equals the total of all credits, providing mathematical proof of accounting accuracy. This is the same principle used by traditional financial institutions.

Use Cases:

  • Detailed financial reconciliation
  • Audit trail generation
  • Accounting system integration
  • Verify balance calculations

get_ledger_transactions

Name

get_ledger_transactions

Usage

Retrieves user-facing transaction history showing transfers, deposits, withdrawals, and app session operations. Unlike ledger entries (which show accounting details), this provides a simplified view of financial activity with sender, receiver, amount, and transaction type. Supports filtering by asset and transaction type. Sorted by creation date (newest first by default).

Request

ParameterTypeRequiredDescriptionDefaultAllowed ValuesExample
account_idstringNoFilter by account identifier--"0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb"
assetstringNoFilter by asset--"usdc"
tx_typestringNoFilter by transaction type-"transfer" | "deposit" | "withdrawal" | "app_deposit" | "app_withdrawal" | "escrow_lock" | "escrow_unlock""transfer"
offsetnumberNoPagination offset0--
limitnumberNoNumber of transactions to return10 (max 100)--
sortstringNoSort order by created_at"desc""asc" | "desc"-

Response

ParameterTypeDescriptionExample
ledger_transactionsarray<LedgerTransaction>List of transactionsSee structure below

LedgerTransaction Structure

FieldTypeDescriptionExample
idnumberUnique transaction identifier1
tx_typestringTransaction type"transfer"
from_accountstringSender account identifier (wallet, channel, or app session)"0x742d35Cc..."
from_account_tagstringSender's user tag (empty if none)"NQKO7C"
to_accountstringReceiver account identifier (wallet, channel, or app session)"0x8B3192f2..."
to_account_tagstringReceiver's user tag (empty if none)"UX123D"
assetstringAsset symbol"usdc"
amountstringTransaction amount"50.0"
created_atstringTransaction timestamp (ISO 8601)"2023-05-01T12:00:00Z"

from_account and to_account mirror the broker’s internal AccountID values, so they can reference wallets, app session escrow accounts, or channel escrows.

Transaction Types

TypeDescriptionDirection
transferDirect transfer between unified balancesOff-chain ↔ Off-chain
depositFunds deposited from channel to unified balanceOn-chain → Off-chain
withdrawalFunds withdrawn from unified balance to channelOff-chain → On-chain
app_depositFunds moved from unified balance into app sessionUnified → App Session
app_withdrawalFunds released from app session to unified balanceApp Session → Unified
escrow_lockFunds temporarily locked for blockchain operationsUnified → Escrow
escrow_unlockFunds released from escrow after blockchain confirmationEscrow → Unified

Use Cases:

  • Display transaction history in UI
  • Export transaction records
  • Monitor specific transaction types
  • Track payment flows

get_rpc_history

Name

get_rpc_history

Usage

Returns the authenticated user's recent RPC invocations, including signed request and response payloads. Useful for audit trails and debugging client integrations.

Request

ParameterTypeRequiredDescriptionDefaultExample
offsetnumberNoPagination offset020
limitnumberNoMaximum entries to return10 (max 100)25
sortstringNoSort order by timestamp"desc""asc"

Response

ParameterTypeDescriptionSee Also
rpc_entriesarray<RPCEntry>Recorded invocationsSee structure below

RPCEntry Structure

FieldTypeDescription
idnumberInternal history identifier
senderstringWallet that issued the call
req_idnumberRequest sequence number
methodstringRPC method name
paramsstringJSON-encoded request parameters
timestampnumberUnix timestamp (seconds)
req_sigarray<Signature>Signatures attached to the request
responsestringJSON-encoded response payload
res_sigarray<Signature>Response signatures

Use Cases:

  • Debug client/server mismatches
  • Provide user-facing audit logs
  • Verify signed payloads during dispute resolution

get_user_tag

Name

get_user_tag

Usage

Retrieves the authenticated user's unique alphanumeric tag. User tags provide a human-readable alternative to addresses for transfer operations, similar to username systems. Tags are automatically generated upon first interaction with a clearnode and remain constant. This is a convenience feature for improving user experience.

Request

No parameters.

Response

ParameterTypeDescriptionFormatExampleNotes
tagstringUser's unique alphanumeric tag6 uppercase alphanumeric characters"UX123D"Can be used in transfer operations as destination_user_tag

Usage in Transfers

Instead of using full address:

transfer({destination: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb", ...})

Users can use the tag:

transfer({destination_user_tag: "UX123D", ...})
Human-Readable Addresses

User tags make it easier for users to share their "address" verbally or in non-technical contexts, similar to payment apps like Venmo or Cash App usernames.


get_session_keys

Name

get_session_keys

Usage

Retrieves all active (non-expired) session keys for the authenticated user. Shows each session key's address, application name, spending allowances, current usage, expiration, and permissions. Used for managing delegated keys and monitoring spending caps. Only returns session keys (not custody signers).

Authentication

Required (private method)

Request

ParameterTypeRequiredDescriptionDefaultExample
offsetnumberNoPagination offset020
limitnumberNoResults per page10 (max 100)25
sortstringNoSort order by created_at"desc""asc"

Response

ParameterTypeDescriptionSee Also
session_keysarray<SessionKeyInfo>List of active session keysSee structure below

SessionKeyInfo Structure

FieldTypeDescriptionDefaultNotes
idnumberInternal identifier
session_keystring (address)Session key address
applicationstringApplication name for this session"clearnode"
allowancesarray<AllowanceUsage>Spending limits and usageSee structure below
scopestringPermission scopeFuture feature, not fully enforced yet
expires_atstring (timestamp)Session expiration time (ISO 8601 format)
created_atstring (timestamp)Session creation time (ISO 8601 format)

Example:

{
"id": 1,
"session_key": "0x9876543210fedcba...",
"application": "Chess Game",
"allowances": [
{"asset": "usdc", "allowance": "100.0", "used": "45.0"}
],
"scope": "app.create,transfer",
"expires_at": "2023-05-02T12:00:00Z",
"created_at": "2023-05-01T12:00:00Z"
}

AllowanceUsage

FieldTypeDescription
assetstringAsset identifier (e.g., "usdc")
allowancestringTotal spending limit
usedstringAmount already spent

Spending Tracking

The clearnode tracks session key spending by monitoring all ledger debit operations:

Initial: allowance = 100 USDC, used = 0 USDC
After transfer of 45 USDC: allowance = 100 USDC, used = 45 USDC
Remaining = 55 USDC available for future operations

When a session key reaches its spending cap, further operations are rejected:

Error: "operation denied: insufficient session key allowance: 60 required, 55 available"
Spending Caps

Session key allowances provide important security: even if a session key is compromised, the maximum loss is limited to the allowance amount.

Use Cases:

  • Display active sessions in UI
  • Monitor spending against caps
  • Manage session lifecycles
  • Security auditing

ping

Name

ping

Usage

Simple connectivity check to verify the clearnode is responsive and the RPC connection is alive. Returns immediately with success. Used for heartbeat, connection testing, and latency measurement.

Authentication

Not required (public method)

Request

No parameters required (empty object {}).

Response

The response method should be "pong".

ParameterTypeDescriptionValue/ExampleNotes
(empty)objectEmpty object or confirmation data{}Response indicates successful connection

Use Cases

Heartbeat: Periodic ping to keep RPC connection alive

setInterval(() => clearnode.call("ping"), 30000)  // Every 30 seconds

Latency Measurement: Measure round-trip time

const start = Date.now()
await clearnode.call("ping")
const latency = Date.now() - start
console.log(`Latency: ${latency}ms`)

Health Check: Verify connection before critical operations

try {
await clearnode.call("ping")
// Connection healthy, proceed with operation
} catch (error) {
// Connection lost, reconnect
}

Authentication Status: Test if session is still valid

const response = await clearnode.call("ping")
// If no auth error, session is active

Notifications (Server-to-Client)

The clearnode sends unsolicited notifications to clients via RPC when certain events occur. These are not responses to requests, but asynchronous messages initiated by the server.

Notification Types

MethodDescriptionData Structure
buBalance updatebalance_updates array with updated balances
cuChannel updateFull Channel object
trTransfer (incoming/outgoing)transactions array with transfer details
asuApp session updateapp_session object and participant_allocations

bu (Balance Update)

Method

bu

When Sent

Whenever account balances change due to transfers, app session operations, or channel operations.

Structure

FieldTypeDescriptionExample
balance_updatesarray<LedgerBalance>Updated balances for affected accountsSee structure below

LedgerBalance Structure

FieldTypeDescriptionExample
assetstringAsset symbol"usdc"
amountstringNew balance amount"150.0"

Use Cases:

  • Update balance display in real-time
  • Trigger UI animations for balance changes
  • Log balance history for analytics

cu (Channel Update)

Method

cu

When Sent

When a channel's state changes (opened, resized, challenged, closed).

Structure

The notification contains the complete updated Channel object. See Channel Structure in the get_channels section for the full field list.

Use Cases:

  • Update channel status in UI
  • Alert user when channel becomes active
  • Monitor for unexpected channel closures

tr (Transfer)

Method

tr

When Sent

When a transfer affects the user's account (both incoming and outgoing transfers).

Structure

FieldTypeDescriptionExample
transactionsarray<LedgerTransaction>Array of transaction objects for the transferSee structure below

The LedgerTransaction structure is identical to the one returned by get_ledger_transactions. See LedgerTransaction Structure for the full field list.

Use Cases:

  • Display incoming/outgoing payment notifications
  • Play sound/show toast for transfers
  • Update transaction history in real-time
Real-Time Payments

Combine tr notifications with bu (balance update) to provide immediate feedback when users send or receive funds.


asu (App Session Update)

Method

asu

When Sent

When an app session state changes (new state submitted, session closed, deposits/withdrawals).

Structure

FieldTypeDescriptionExample
app_sessionAppSessionComplete app session objectSee get_app_sessions for structure
participant_allocationsarray<AppAllocation>Current allocations for each participantSee structure below

AppAllocation Structure

FieldTypeDescriptionExample
participantstringParticipant wallet address"0x742d35Cc..."
assetstringAsset symbol"usdc"
amountstringAllocated amount"50.0"

Use Cases:

  • Update game UI when opponent makes a move
  • Refresh session state in real-time
  • Alert when session is closed
  • Sync multi-participant applications

Implementation Notes

Connection Management:

  • Maintain persistent connection for notifications
  • Implement automatic reconnection on disconnect
  • Re-fetch current state after reconnection

Notification Handling:

  • All notifications are asynchronous
  • No response required from client
  • Multiple notifications may arrive rapidly (batch if needed)

Best Practices:

  • Use query methods for initial state retrieval
  • Use notifications for ongoing monitoring
  • Don't rely solely on notifications (could be missed during disconnect)
  • Implement periodic state refresh as backup

Pagination:

  • For methods with pagination, use reasonable limit values

Next Steps

Explore other protocol features:

For protocol fundamentals: