Helper Methods


The GraphQLClient class is the primary interface for interacting with an OCAP-powered blockchain. It provides a comprehensive set of methods for querying the chain state, sending transactions, and subscribing to real-time events. It is designed to work seamlessly in both Node.js and browser environments.

Client Initialization

const GraphQLClient = require('@ocap/client');

// Connect to the Beta chain
const client = new GraphQLClient('https://beta.abtnetwork.io/api');

(async () => {
  const res = await client.getChainInfo();
  console.log('Connected to chain:', res.info.network);
})();

This section provides a detailed reference for the core helper methods of the GraphQLClient class.

Constructor#

new GraphQLClient(endpoint, autoInit)#

Creates a new instance of the GraphQLClient.

Parameters

endpoint
string
required

The absolute URL of the GraphQL endpoint for the blockchain node (e.g., https://beta.abtnetwork.io/api).

autoInit
boolean
default:true

If true, the client will automatically fetch and cache essential chain information (the "context") upon initialization. This is recommended for most use cases.

Example

Creating a Client Instance

const client = new GraphQLClient('https://beta.abtnetwork.io/api', true);

Core Methods#

These methods provide fundamental functionality for interacting with the client and the chain.

getContext()#

Fetches and caches essential chain information, such as the chain ID, native token details, and transaction fee configurations. This method is called automatically if autoInit is enabled in the constructor. Subsequent calls will return the cached context.

Returns

Promise<object>
object
A promise that resolves to the context object containing chain metadata.
4 subfields

Example

Fetching Chain Context

async function logChainToken() {
  const context = await client.getContext();
  console.log(`Native Token Symbol: ${context.token.symbol}`);
}

logChainToken();

setGasPayer(wallet)#

Configures a wallet to act as a "gas payer." When set, this wallet will sponsor the transaction fees for transactions sent through this client instance, enabling gasless experiences for users. For more details, see the Gas Payment concept guide.

Parameters

wallet
WalletObject
required

A wallet object with address, publicKey, and secretKey properties, equipped with a sign method.

decodeTx(input)#

Deserializes a transaction from various formats into a human-readable JavaScript object.

Parameters

input
Buffer | string
required

The transaction data to decode. Can be a Buffer or a string in hex, base58, or base64 format.

Returns

object
object
The decoded transaction object.

getType(name)#

Retrieves the Protobuf message class for a given type name. This is useful for advanced scenarios where you need to manually construct or inspect Protobuf messages.

Parameters

name
string
required
The name of the Protobuf message type (e.g., 'Transaction', 'TransferTx').

Returns

class | null
object
The message class constructor, or null if not found.


Event Subscription#

The client supports real-time event subscriptions over WebSockets, allowing your application to react instantly to on-chain events.

subscribe(topic, callback)#

Establishes a WebSocket connection and subscribes to a specific event topic.

Parameters

topic
string
required
The event topic to subscribe to (e.g., 'newBlock', 'tx:transfer').
callback
function
required
A function to execute when an event is received. It receives the event payload as its only argument.

unsubscribe(topic, callback)#

Removes a previously registered callback for a specific topic.

Parameters

topic
string
required
The event topic to unsubscribe from.
callback
function
required
The specific callback function to remove.

Example

Subscribing to New Blocks

const handleNewBlock = (block) => {
  console.log(`New block received! Height: ${block.height}`);
  
  // Unsubscribe after receiving one block
  client.unsubscribe('newBlock', handleNewBlock);
  console.log('Unsubscribed from newBlock events.');
};

client.subscribe('newBlock', handleNewBlock);
console.log('Subscribed to newBlock events...');

Token Utility Methods#

These helpers simplify conversions between the human-readable token amount and the on-chain base unit representation.

fromUnitToToken(value)#

Converts a value from the chain's base unit (a large integer string) to a standard decimal string, based on the native token's decimal places.

Parameters

value
string
required
The amount in the chain's base unit.

Returns

string
string
The amount in the standard token unit.

fromTokenToUnit(amount)#

Converts a standard decimal amount into the chain's base unit representation (a BN.js instance).

Parameters

amount
number | string
required
The token amount in its standard decimal form.

Returns

BN
object
A BN.js instance representing the value in the chain's base unit.

Example

Token Amount Conversion

async function convertToken() {
  // Convert 100 TBA to its base unit
  const unitAmount = await client.fromTokenToUnit(100);
  console.log(`100 TBA is ${unitAmount.toString()} in base units.`);

  // Convert it back
  const tokenAmount = await client.fromUnitToToken(unitAmount.toString());
  console.log(`${unitAmount.toString()} base units is ${tokenAmount} TBA.`);
}

convertToken();

Method Discovery#

The client dynamically generates methods for every transaction type supported by the connected OCAP node. These discovery methods allow you to programmatically list all available transaction-related functions.

getTxSendMethods()#

Returns an array of all available send...Tx method names. These methods handle the full lifecycle of signing and sending a transaction.

getTxEncodeMethods()#

Returns an array of all available encode...Tx method names. These methods prepare and serialize a transaction into a buffer, but do not sign it.

getTxSignMethods()#

Returns an array of all available sign...Tx method names. These methods encode and then sign a transaction, returning the signed transaction object.

getTxMultiSignMethods()#

Returns an array of all available multiSign...Tx method names, used for multi-signature workflows.

Example

Listing Available Transaction Methods

const sendMethods = client.getTxSendMethods();
console.log('Available send methods:', sendMethods);
// Example output: [ 'sendPokeTx', 'sendTransferTx', ... ]