Used to check for browser translation.
用于检测浏览器翻译。
ブラウザの翻訳を検出する

API Reference


The @ocap/client library is the primary SDK for connecting your applications to an OCAP blockchain node. It provides a comprehensive set of tools for querying the blockchain state, creating and sending transactions, and subscribing to real-time events. This document serves as a complete reference for all its methods, data structures, and enumerations.

Before diving into the API details, it's helpful to have a solid understanding of the core concepts of the OCAP. We recommend reviewing the following guides:

The client is available on npm and the source code is on GitHub.

Client Initialization#

To begin, you need to instantiate the GraphQLClient.

new GraphQLClient(endpoint, autoInit)#

Creates a new client instance that connects to a specific OCAP node.

Parameters

Name

Type

Description

endpoint

string

The HTTP/HTTPS endpoint of the OCAP node's GraphQL interface.

autoInit

boolean

(Optional, default: true) If true, the client automatically fetches chain context like chainId and token info upon initialization.

Example

import GraphQLClient from '@ocap/client';

const endpoint = 'https://beta.abtnetwork.io/api/v2/gql';
const client = new GraphQLClient(endpoint);

async function getChainInfo() {
const result = await client.getChainInfo();
console.log(result.info);
}

getChainInfo();

Querying Blockchain Data#

The client provides a set of methods for querying various states and information from the blockchain. These methods correspond directly to the queries available in the OCAP GraphQL schema.

Here is a summary of the available query methods:

Method

Description

getAccountState(params)

Retrieves the state of a specific account.

getAssetState(params)

Retrieves the state of a specific asset (NFT).

getFactoryState(params)

Retrieves the state of a specific asset factory.

getDelegateState(params)

Retrieves the state of a delegation.

getTokenState(params)

Retrieves the state of a specific token.

getForgeState(params)

Retrieves the global state and configuration of the chain.

getStakeState(params)

Retrieves the state of a specific stake.

getArcBridgeState(params)

Retrieves the state of a specific ArcBridge.

getTx(params)

Retrieves detailed information about a single transaction by its hash.

getBlock(params)

Retrieves a full block by its height.

getBlocks(params)

Retrieves a paginated list of simplified block information.

getUnconfirmedTxs(params)

Retrieves a list of transactions in the mempool.

getChainInfo()

Retrieves general information about the blockchain.

getNodeInfo()

Retrieves information about the connected node.

getValidatorsInfo()

Retrieves information about the current set of validators.

getForgeStats()

Retrieves statistical data about the chain.

listTransactions(params)

Lists transactions with powerful filtering capabilities.

listAssets(params)

Lists assets, optionally filtered by owner or factory.

listTopAccounts(params)

Lists accounts with the highest token balances.

listStakes(params)

Lists stakes, with filters for sender, receiver, and assets.

listArcBridges(params)

Lists ArcBridges, with filters for associated tokens.

listArcBridgeBlocks(params)

Lists blocks created within an ArcBridge.

Example: getAccountState#

Fetches the current state of an account, including its balance, nonce, and owned tokens.

async function checkAccount(address) {
try {
const { state } = await client.getAccountState({ address });
if (state) {
console.log('Account Moniker:', state.moniker);
console.log('Balance:', state.balance);
console.log('Nonce:', state.nonce);
} else {
console.log('Account not found.');
}
} catch (error) {
console.error('Error fetching account state:', error);
}
}

checkAccount('z1_TBA_YOUR_ACCOUNT_ADDRESS');

Example Response

{
"code": "OK",
"state": {
"balance": "100000000000000000000",
"nonce": "123",
"numTxs": "42",
"address": "z1_TBA_YOUR_ACCOUNT_ADDRESS",
"pk": "...",
"type": {
"role": "ROLE_ACCOUNT",
"pk": "ED25519",
"hash": "SHA3",
"address": "BASE58"
},
"moniker": "MyAccount",
"context": { ... },
"issuer": "",
"gasBalance": "0",
"migratedTo": [],
"migratedFrom": [],
"numAssets": "5",
"tokens": [],
"data": null
}
}

Sending Transactions (Mutations)#

The client simplifies the process of creating, signing, and sending transactions. It provides high-level abstraction methods for common operations, which internally handle encoding, signing, and broadcasting.

The typical transaction flow is as follows:

OCAP NodeWallet@ocap/clientApplicationOCAP NodeWallet@ocap/clientApplicationCalls high-level method, e.g., transfer({ to, token, wallet })1. Constructs the inner transaction (ITX)2. Encodes the full transaction3. Signs the encoded transaction bufferReturns signature4. Sends signed transaction via sendTx mutationTransaction hashReturns transaction hash

High-Level Transaction Methods#

These methods provide a simplified interface for the most common transaction types.

transfer(params, extra)#

Transfers the native token or other tokens/assets to a recipient.

Parameters

Name

Type

Description

params.to

string

The recipient's address.

params.token

number

(Optional) The amount of the native chain token to transfer.

params.tokens

TokenInput[]

(Optional) An array of other tokens to transfer. [{ address, value }].

params.assets

string[]

(Optional) An array of asset addresses to transfer.

params.wallet

WalletObject

The sender's wallet object for signing.

params.memo

string

(Optional) A memo for the transaction.

extra

object

(Optional) Extra parameters for the underlying GraphQL client.

Example

import { fromRandom } from '@ocap/wallet';

async function sendTokens() {
const wallet = fromRandom(); // In a real app, load a wallet with funds
const recipient = 'z1_TBA_RECIPIENT_ADDRESS';

try {
const hash = await client.transfer({
to: recipient,
token: 10, // transfer 10 native tokens
wallet: wallet,
memo: 'Here are the tokens I promised'
});
console.log('Transfer transaction sent, hash:', hash);
} catch (error) {
console.error('Transfer failed:', error);
}
}

sendTokens();

createAsset(params, extra)#

Creates a new, unique asset (NFT) on the blockchain.

Parameters

Name

Type

Description

params.moniker

string

A human-readable name for the asset.

params.data

object

A JSON object containing custom data for the asset.

params.wallet

WalletObject

The wallet that will own the new asset.

params.readonly

boolean

(Optional, default: false) If true, the asset's data cannot be changed after creation.

params.transferrable

boolean

(Optional, default: true) If true, the asset can be transferred to others.

Example

import { fromRandom } from '@ocap/wallet';

async function issueCertificate() {
const wallet = fromRandom(); // Wallet of the issuer/owner

try {
const [hash, address] = await client.createAsset({
moniker: 'Certificate of Completion',
data: {
typeUrl: 'json',
value: {
course: 'Blockchain Development 101',
recipient: 'z1_TBA_STUDENT_ADDRESS',
issueDate: new Date().toISOString(),
}
},
wallet: wallet,
readonly: true
});
console.log('Asset created, hash:', hash);
console.log('Asset address:', address);
} catch (error) {
console.error('Asset creation failed:', error);
}
}

issueCertificate();

Low-Level Transaction Helpers#

For advanced use cases, such as creating transactions offline or implementing custom signing solutions, you can use the lower-level helper methods.

Method Prefix

Description

encode<TxName>Tx

Encodes a transaction into a buffer and object, ready for signing.

sign<TxName>Tx

Encodes and then signs a transaction, returning the full signed transaction object.

multiSign<TxName>Tx

Adds a signature to a multi-signature transaction.

send<TxName>Tx

Sends a pre-signed transaction to the blockchain.

Subscribing to Events#

The client supports real-time event subscriptions via WebSockets, allowing your application to react instantly to new blocks and transactions.

doRawSubscription(query)#

Establishes a subscription to a GraphQL endpoint.

Example: Subscribing to New Blocks

const subscription = client.doRawSubscription(`
subscription {
newBlock {
height
numTxs
time
}
}
`);

subscription.on('data', (data) => {
console.log('New Block Received:', data.newBlock);
});

subscription.on('error', (error) => {
console.error('Subscription Error:', error);
});

Utility Methods#

Method

Description

fromUnitToToken(value)

Converts a raw token amount (in the smallest unit) to a user-friendly decimal format.

fromTokenToUnit(amount)

Converts a decimal token amount into its raw smallest unit representation (as a BN.js object).

decodeTx(input)

Decodes a transaction from buffer, hex, base58, or base64 into a readable object.

getType(name)

Retrieves the Protobuf message class for a given Forge type.

Core Enums#

These enumerations define the constant values used throughout the OCAP.

RoleType#

Defines the role of a DID address.

Value

Description

ROLE_ACCOUNT

A standard user account.

ROLE_NODE

A blockchain node.

ROLE_ASSET

An asset (NFT).

ROLE_TOKEN

A token contract.

ROLE_FACTORY

An asset factory.

ROLE_STAKE

A stake address.

ROLE_ARCBRIDGE

An ArcBridge contract.

ROLE_ANY

Can represent any role.

StatusCode#

Represents the result code of a transaction after it has been processed.

Value

Description

OK

The transaction was successful.

INVALID_NONCE

The transaction nonce was incorrect.

INVALID_SIGNATURE

The transaction signature was invalid.

INSUFFICIENT_FUND

The sender has insufficient funds.

INVALID_ASSET

The specified asset is invalid or does not exist.

EXPIRED_TX

The transaction has expired.

FORBIDDEN

The operation is not allowed.

INTERNAL

An internal server error occurred.


This reference provides a comprehensive overview of the @ocap/client library. For practical examples and walkthroughs, please refer to the Getting Started guide and the Transaction Types section.