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

Getting Started


This section guides you through the initial setup of the @ocap/client library, a powerful client for connecting your applications to ArcBlock's OCAP (Blockchain) nodes. It simplifies interactions with the blockchain, allowing you to query data, send transactions, and subscribe to real-time events over HTTP/HTTPS. The library is versatile, designed for use in both Node.js and browser environments.

For a general introduction to the @ocap/client library and its core capabilities, refer to the Overview.

Installation#

To begin using the @ocap/client library, install it via npm or pnpm in your project:

npm i @ocap/client -S
# OR
pnpm install @ocap/client

Initializing the GraphQLClient#

To interact with a blockchain node, you first need to create an instance of GraphQLClient. The client requires the blockchain node's GraphQL API endpoint.

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

/**
* Create an instance of GraphQLClient
*
* @constructor
* @param {string} endpoint the graphql endpoint of the chain. Must be a valid absolute URL (e.g., 'http://localhost:8210/api' or 'https://beta.abtnetwork.io/api').
* @param {boolean} [autoInit=true] whether to automatically warm up the context on initialization. Defaults to true.
*/
const client = new GraphQLClient('http://localhost:8210/api');

Once initialized, the client object provides access to various methods for interacting with the blockchain. You can inspect the available methods like this:

console.log({
queries: client.getQueries(),
mutations: client.getMutations(),
subscriptions: client.getSubscriptions(),
senders: client.getTxSendMethods(),
encoders: client.getTxEncodeMethods(),
});

This will output a list of all available query, mutation, subscription, sender (shortcut for signing and sending transactions), and encoder (shortcut for encoding transactions) methods that the client can use.

Performing Your First Query#

The GraphQLClient allows you to easily query various types of blockchain data. Here's how you can fetch basic chain information and block data:

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

const client = new GraphQLClient('http://localhost:8210/api');

(async () => {
try {
// Query chain state data
const chainInfo = await client.getChainInfo();
const forgeState = await client.getForgeState();
const block = await client.getBlock({ height: 2 });

console.log('Chain Information:', chainInfo);
console.log('Forge State:', forgeState);
console.log('Block at height 2:', block);
} catch (error) {
console.error('Error fetching data:', error);
}
})();

This example demonstrates how to use getChainInfo() to retrieve general information about the blockchain, getForgeState() for the current state of the Forge chain, and getBlock() to get details of a specific block by its height.

Sending Your First Transaction#

Sending transactions to the blockchain involves creating a wallet, defining the transaction details, and then sending it. The client provides convenient helper methods for common transaction types. Below is an example of declaring a new identity (account) on the blockchain:

const Mcrypto = require('@ocap/mcrypto');
const GraphQLClient = require('@ocap/client');
const { fromRandom, WalletType } = require('@ocap/wallet');

const client = new GraphQLClient('http://localhost:8210/api');

(async () => {
try {
// Create a new random wallet for the account
const wallet = fromRandom(
WalletType({
role: Mcrypto.types.RoleType.ROLE_ACCOUNT,
pk: Mcrypto.types.KeyType.SECP256K1,
hash: Mcrypto.types.HashType.SHA3,
})
);

// Declare a new identity on the blockchain using the generated wallet
// The `declare` method is a shortcut that handles signing and sending the transaction.
const hash = await client.declare({
moniker: 'my_unique_username',
wallet,
});

console.log('Declare transaction hash:', hash);
console.log(`View your new account here: http://localhost:8210/explorer/accounts/${wallet.address}`);
console.log(`View your transaction here: http://localhost:8210/explorer/txs/${hash}`);
} catch (error) {
console.error('Error declaring account:', error);
}
})();

This example first generates a new random wallet that will represent your on-chain account. Then, it uses the client.declare() method to send a DeclareTx transaction to the blockchain, registering a new identity with a specified moniker. The declare method automatically handles the necessary signing and broadcasting of the transaction for convenience.

Debugging#

To enable detailed debug logs for the @ocap/client library, you can set the DEBUG environment variable or localStorage item:

  • In Node.js: Set the DEBUG environment variable before running your script:DEBUG=@ocap/client node script.js
    # OR for all @ocap packages:
    DEBUG=@ocap/* node script.js

  • In the Browser: Set a localStorage item in your browser's developer console:localStorage.setItem('DEBUG', '@ocap/client');
    // OR for all @ocap packages:
    localStorage.setItem('DEBUG', '@ocap/*');


You've now successfully installed the @ocap/client library, initialized it, performed a basic query, and sent your first transaction. To dive deeper into the full range of functionalities for querying, sending transactions, and subscribing to events, proceed to the Client Capabilities section.