# 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.

```javascript Client Initialization icon=logos:javascript
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**

<x-field-group>
  <x-field data-name="endpoint" data-type="string" data-required="true">
    <x-field-desc markdown>The absolute URL of the GraphQL endpoint for the blockchain node (e.g., `https://beta.abtnetwork.io/api`).</x-field-desc>
  </x-field>
  <x-field data-name="autoInit" data-type="boolean" data-default="true" data-required="false">
    <x-field-desc markdown>If `true`, the client will automatically fetch and cache essential chain information (the "context") upon initialization. This is recommended for most use cases.</x-field-desc>
  </x-field>
</x-field-group>

**Example**

```javascript Creating a Client Instance icon=logos:javascript
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**

<x-field data-name="Promise<object>" data-type="object" data-desc="A promise that resolves to the context object containing chain metadata.">
  <x-field data-name="chainId" data-type="string" data-desc="The unique identifier of the blockchain network."></x-field>
  <x-field data-name="consensus" data-type="string" data-desc="The consensus engine version."></x-field>
  <x-field data-name="token" data-type="object" data-desc="Information about the native token.">
    <x-field data-name="address" data-type="string" data-desc="The address of the native token contract."></x-field>
    <x-field data-name="decimal" data-type="number" data-desc="The number of decimal places for the native token."></x-field>
    <x-field data-name="symbol" data-type="string" data-desc="The symbol of the native token (e.g., TBA)."></x-field>
  </x-field>
  <x-field data-name="txConfig" data-type="object" data-desc="Transaction fee and gas configuration."></x-field>
</x-field>

**Example**

```javascript Fetching Chain Context icon=logos:javascript
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](./core-concepts-gas-payment.md) concept guide.

**Parameters**

<x-field data-name="wallet" data-type="WalletObject" data-required="true">
  <x-field-desc markdown>A wallet object with `address`, `publicKey`, and `secretKey` properties, equipped with a `sign` method.</x-field-desc>
</x-field>

### decodeTx(input)

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

**Parameters**

<x-field data-name="input" data-type="Buffer | string" data-required="true">
  <x-field-desc markdown>The transaction data to decode. Can be a `Buffer` or a string in `hex`, `base58`, or `base64` format.</x-field-desc>
</x-field>

**Returns**

<x-field data-name="object" data-type="object" data-desc="The decoded transaction object."></x-field>

### 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**

<x-field data-name="name" data-type="string" data-required="true" data-desc="The name of the Protobuf message type (e.g., 'Transaction', 'TransferTx')."></x-field>

**Returns**

<x-field data-name="class | null" data-type="object" data-desc="The message class constructor, or null if not found."></x-field>

---


## 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**

<x-field-group>
  <x-field data-name="topic" data-type="string" data-required="true" data-desc="The event topic to subscribe to (e.g., 'newBlock', 'tx:transfer')."></x-field>
  <x-field data-name="callback" data-type="function" data-required="true" data-desc="A function to execute when an event is received. It receives the event payload as its only argument."></x-field>
</x-field-group>

### unsubscribe(topic, callback)

Removes a previously registered callback for a specific topic.

**Parameters**

<x-field-group>
  <x-field data-name="topic" data-type="string" data-required="true" data-desc="The event topic to unsubscribe from."></x-field>
  <x-field data-name="callback" data-type="function" data-required="true" data-desc="The specific callback function to remove."></x-field>
</x-field-group>

**Example**

```javascript Subscribing to New Blocks icon=logos:javascript
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**

<x-field data-name="value" data-type="string" data-required="true" data-desc="The amount in the chain's base unit."></x-field>

**Returns**

<x-field data-name="string" data-type="string" data-desc="The amount in the standard token unit."></x-field>

### fromTokenToUnit(amount)

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

**Parameters**

<x-field data-name="amount" data-type="number | string" data-required="true" data-desc="The token amount in its standard decimal form."></x-field>

**Returns**

<x-field data-name="BN" data-type="object" data-desc="A BN.js instance representing the value in the chain's base unit."></x-field>

**Example**

```javascript Token Amount Conversion icon=logos:javascript
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**

```javascript Listing Available Transaction Methods icon=logos:javascript
const sendMethods = client.getTxSendMethods();
console.log('Available send methods:', sendMethods);
// Example output: [ 'sendPokeTx', 'sendTransferTx', ... ]
```
