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 |
---|---|---|
|
| The HTTP/HTTPS endpoint of the OCAP node's GraphQL interface. |
|
| (Optional, default: |
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 |
---|---|
| Retrieves the state of a specific account. |
| Retrieves the state of a specific asset (NFT). |
| Retrieves the state of a specific asset factory. |
| Retrieves the state of a delegation. |
| Retrieves the state of a specific token. |
| Retrieves the global state and configuration of the chain. |
| Retrieves the state of a specific stake. |
| Retrieves the state of a specific ArcBridge. |
| Retrieves detailed information about a single transaction by its hash. |
| Retrieves a full block by its height. |
| Retrieves a paginated list of simplified block information. |
| Retrieves a list of transactions in the mempool. |
| Retrieves general information about the blockchain. |
| Retrieves information about the connected node. |
| Retrieves information about the current set of validators. |
| Retrieves statistical data about the chain. |
| Lists transactions with powerful filtering capabilities. |
| Lists assets, optionally filtered by owner or factory. |
| Lists accounts with the highest token balances. |
| Lists stakes, with filters for sender, receiver, and assets. |
| Lists ArcBridges, with filters for associated tokens. |
| 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:
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 |
---|---|---|
|
| The recipient's address. |
|
| (Optional) The amount of the native chain token to transfer. |
|
| (Optional) An array of other tokens to transfer. |
|
| (Optional) An array of asset addresses to transfer. |
|
| The sender's wallet object for signing. |
|
| (Optional) A memo for the transaction. |
|
| (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 |
---|---|---|
|
| A human-readable name for the asset. |
|
| A JSON object containing custom data for the asset. |
|
| The wallet that will own the new asset. |
|
| (Optional, default: |
|
| (Optional, default: |
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 |
---|---|
| Encodes a transaction into a buffer and object, ready for signing. |
| Encodes and then signs a transaction, returning the full signed transaction object. |
| Adds a signature to a multi-signature transaction. |
| 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 |
---|---|
| Converts a raw token amount (in the smallest unit) to a user-friendly decimal format. |
| Converts a decimal token amount into its raw smallest unit representation (as a BN.js object). |
| Decodes a transaction from buffer, hex, base58, or base64 into a readable object. |
| 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 |
---|---|
| A standard user account. |
| A blockchain node. |
| An asset (NFT). |
| A token contract. |
| An asset factory. |
| A stake address. |
| An ArcBridge contract. |
| Can represent any role. |
StatusCode
#
Represents the result code of a transaction after it has been processed.
Value | Description |
---|---|
| The transaction was successful. |
| The transaction nonce was incorrect. |
| The transaction signature was invalid. |
| The sender has insufficient funds. |
| The specified asset is invalid or does not exist. |
| The transaction has expired. |
| The operation is not allowed. |
| 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.