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

Querying Blockchain Data


The @arcblock/graphql-client library provides a comprehensive set of methods to query various types of data from a Forge-powered blockchain node. These methods allow you to retrieve real-time information about the chain's state, blocks, transactions, accounts, assets, and more. Understanding these querying capabilities is fundamental to building applications that interact with the blockchain.

For an overview of all client functionalities, refer to the Client Capabilities section. To learn about sending data to the blockchain, see Sending Transactions (Mutations).

Get General Chain Information#

Retrieve fundamental information about the blockchain network and its current state.

getChainInfo()#

This method fetches general information about the connected blockchain, such as its network ID, consensus version, and block details.

Returns

Name

Type

Description

code

string

Status code of the response (e.g., "OK").

info

ChainInfo

Object containing chain details.

ChainInfo Structure

Field

Type

Description

id

string

Unique identifier of the chain.

network

string

Name of the network.

moniker

string

Moniker of the chain.

consensusVersion

string

Version of the consensus engine.

synced

boolean

Indicates if the node is synced with the chain.

blockHeight

string

Current block height.

blockTime

string

Timestamp of the latest block.

totalTxs

string

Total number of transactions on the chain.

Example

import GraphQLClient from '@ocap/client';

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

(async () => {
try {
const chainInfo = await client.getChainInfo();
console.log('Chain Information:', chainInfo.info);
// Output example:
// Chain Information: { id: '...', network: '...', blockHeight: '...', ... }
} catch (error) {
console.error('Error fetching chain info:', error);
}
})();

This example demonstrates how to retrieve and log the basic information of the blockchain.

getForgeState()#

This method retrieves the global state of the Forge blockchain, including token configuration, transaction fees, and upgrade information.

Returns

Name

Type

Description

code

string

Status code of the response.

state

ForgeState

Object containing the global Forge state.

ForgeState Structure (Key Fields)

Field

Type

Description

address

string

Address of the Forge state.

token

ForgeToken

Details about the native token (symbol, decimal, etc.).

txConfig

TransactionConfig

Configuration for transaction fees and gas.

version

string

Version of the Forge SDK.

vaults

VaultConfig

Configuration for various vaults (e.g., slashed stake).

Example

import GraphQLClient from '@ocap/client';

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

(async () => {
try {
const forgeState = await client.getForgeState();
console.log('Forge State Token Symbol:', forgeState.state.token.symbol);
console.log('Forge State Tx Fee Config:', forgeState.state.txConfig.txFee);
// Output example:
// Forge State Token Symbol: ABT
// Forge State Tx Fee Config: [...]
} catch (error) {
console.error('Error fetching forge state:', error);
}
})();

This example shows how to access the native token symbol and transaction fee configuration from the Forge global state.

Explore Blocks and Transactions#

Query specific blocks or transactions, or list them with pagination and filters.

getBlock(params)#

Retrieves a specific block by its height.

Parameters

Name

Type

Description

height

number

The height of the block to retrieve.

Returns

Name

Type

Description

code

string

Status code of the response.

block

BlockInfo

Object containing block details.

BlockInfo Structure (Key Fields)

Field

Type

Description

height

string

The height of the block.

numTxs

number

Number of transactions in the block.

time

string

Timestamp of the block.

proposer

string

Address of the block proposer.

txs

TransactionInfo[]

Array of transactions included in the block.

Example

import GraphQLClient from '@ocap/client';

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

(async () => {
try {
const block = await client.getBlock({ height: 2 });
console.log('Block at height 2:', block.block.height, 'Txs:', block.block.numTxs);
// Output example:
// Block at height 2: 2 Txs: 1
} catch (error) {
console.error('Error fetching block:', error);
}
})();

This example fetches and displays details for the block at height 2.

getTx(params)#

Retrieves a specific transaction by its hash.

Parameters

Name

Type

Description

hash

string

The hash of the transaction to retrieve.

Returns

Name

Type

Description

code

string

Status code of the response.

info

TransactionInfo

Object containing transaction details.

TransactionInfo Structure (Key Fields)

Field

Type

Description

hash

string

The unique hash of the transaction.

sender

string

The sender's address.

receiver

string

The receiver's address.

time

string

Timestamp of the transaction.

type

string

Type of the transaction (e.g., DeclareTx, TransferTx).

valid

boolean

Indicates if the transaction is valid.

Example

import GraphQLClient from '@ocap/client';

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

(async () => {
const txHash = 'YOUR_TRANSACTION_HASH'; // Replace with an actual transaction hash
try {
const txInfo = await client.getTx({ hash: txHash });
console.log('Transaction Info:', txInfo.info.hash, 'Type:', txInfo.info.type);
// Output example:
// Transaction Info: 0x... Type: DeclareTx
} catch (error) {
console.error('Error fetching transaction:', error);
}
})();

This example retrieves and logs the details of a specific transaction using its hash.

listBlocks(params)#

Lists blocks with optional pagination and filters. This is useful for exploring the blockchain's history.

Parameters

Name

Type

Description

paging

PageInput

Optional. Pagination parameters including cursor, size, and order.

proposer

string

Optional. Filter blocks by proposer address.

timeFilter

TimeFilterInput

Optional. Filter blocks by creation time range.

heightFilter

RangeFilterInput

Optional. Filter blocks by height range.

Returns

Name

Type

Description

code

string

Status code of the response.

page

PageInfo

Pagination information.

blocks

IndexedBlock[]

Array of simplified block objects.

PageInput Structure

Field

Type

Description

cursor

string

A cursor for pagination, used to get the next page.

size

number

Number of items per page.

order

PageOrderInput[]

Array of objects to specify sorting order (e.g., [{ field: 'height', type: 'DESC' }]).

IndexedBlock Structure (Key Fields)

Field

Type

Description

height

string

The height of the block.

time

string

Timestamp of the block.

proposer

string

Address of the block proposer.

numTxs

string

Number of transactions in the block.

Example

import GraphQLClient from '@ocap/client';

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

(async () => {
try {
const latestBlocks = await client.listBlocks({
paging: { size: 5, order: [{ field: 'height', type: 'DESC' }] },
});
console.log('Latest 5 Blocks:');
latestBlocks.blocks.forEach(block => {
console.log(`- Height: ${block.height}, Txs: ${block.numTxs}, Time: ${block.time}`);
});
// Output example:
// Latest 5 Blocks:
// - Height: 100, Txs: 5, Time: 2023-01-01T12:00:00Z
// ...
} catch (error) {
console.error('Error listing blocks:', error);
}
})();

This example retrieves the 5 most recent blocks.

listTransactions(params)#

Lists transactions with various filtering and pagination options. This is powerful for auditing and analytical purposes.

Parameters

Name

Type

Description

paging

PageInput

Optional. Pagination parameters.

timeFilter

TimeFilterInput

Optional. Filter by transaction time range.

addressFilter

AddressFilterInput

Optional. Filter by sender/receiver address and direction.

typeFilter

TypeFilterInput

Optional. Filter by transaction type (e.g., ['DeclareTx', 'TransferTx']).

validityFilter

ValidityFilterInput

Optional. Filter by transaction validity (VALID, INVALID, BOTH).

assetFilter

AssetFilterInput

Optional. Filter by assets involved.

tokenFilter

TokenFilterInput

Optional. Filter by tokens involved.

Returns

Name

Type

Description

code

string

Status code of the response.

page

PageInfo

Pagination information.

transactions

IndexedTransaction[]

Array of indexed transaction objects.

IndexedTransaction Structure (Key Fields)

Field

Type

Description

hash

string

The unique hash of the transaction.

sender

string

The sender's address.

receiver

string

The receiver's address.

time

string

Timestamp of the transaction.

type

string

Type of the transaction.

valid

boolean

Indicates if the transaction is valid.

Example

import GraphQLClient from '@ocap/client';
import { WalletType } from '@ocap/wallet';
import Mcrypto from '@ocap/mcrypto';

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

(async () => {
try {
// List all DeclareTx transactions
const declareTxs = await client.listTransactions({
typeFilter: { types: ['DeclareTx'] },
paging: { size: 10, order: [{ field: 'time', type: 'DESC' }] },
});

console.log('Latest 10 Declare Transactions:');
declareTxs.transactions.forEach(tx => {
console.log(`- Hash: ${tx.hash}, Sender: ${tx.sender}, Time: ${tx.time}`);
});

// List transactions involving a specific account
const accountAddress = 'YOUR_ACCOUNT_ADDRESS'; // Replace with an actual account address
const accountTxs = await client.listTransactions({
addressFilter: { sender: accountAddress, direction: 'UNION' },
paging: { size: 5, order: [{ field: 'time', type: 'DESC' }] },
});

console.log(`Latest 5 Transactions for ${accountAddress}:`);
accountTxs.transactions.forEach(tx => {
console.log(`- Hash: ${tx.hash}, Type: ${tx.type}, Time: ${tx.time}`);
});
} catch (error) {
console.error('Error listing transactions:', error);
}
})();

These examples demonstrate listing transactions by type and by involvement of a specific account, using pagination and ordering.

Retrieve Account and Asset States#

Access detailed information about individual accounts and NFTs (assets) on the blockchain.

getAccountState(params)#

Retrieves the current state of a specific account by its address.

Parameters

Name

Type

Description

address

string

The address of the account.

height

string

Optional. The block height at which to query the account state.

keys

string[]

Optional. A list of specific fields to retrieve from the state.

traceMigration

boolean

Optional. If true, traces account migration history.

Returns

Name

Type

Description

code

string

Status code of the response.

state

AccountState

Object containing account details.

AccountState Structure (Key Fields)

Field

Type

Description

address

string

The unique address of the account.

balance

string

The account's main token balance.

nonce

string

The account's transaction nonce.

numTxs

string

Total number of transactions sent by the account.

moniker

string

The account's registered name.

tokens

IndexedTokenInput[]

List of other tokens held by the account.

Example

import GraphQLClient from '@ocap/client';

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

(async () => {
const accountAddress = 'YOUR_ACCOUNT_ADDRESS'; // Replace with an actual account address
try {
const accountState = await client.getAccountState({ address: accountAddress });
console.log(`Account State for ${accountAddress}:`);
console.log(`- Moniker: ${accountState.state.moniker || 'N/A'}`);
console.log(`- Balance: ${accountState.state.balance}`);
console.log(`- Total Transactions: ${accountState.state.numTxs}`);
// Output example:
// Account State for z1...:
// - Moniker: myusername
// - Balance: 100000000000000000
// - Total Transactions: 5
} catch (error) {
console.error('Error fetching account state:', error);
}
})();

This example retrieves and displays the moniker, balance, and total transactions for a given account address.

getAssetState(params)#

Retrieves the current state of a specific asset (NFT) by its address.

Parameters

Name

Type

Description

address

string

The address of the asset.

height

string

Optional. The block height at which to query the asset state.

keys

string[]

Optional. A list of specific fields to retrieve from the state.

Returns

Name

Type

Description

code

string

Status code of the response.

state

AssetState

Object containing asset details.

AssetState Structure (Key Fields)

Field

Type

Description

address

string

The unique address of the asset.

owner

string

The current owner's address.

moniker

string

The name or moniker of the asset.

readonly

boolean

Indicates if the asset can be updated.

transferrable

boolean

Indicates if the asset can be transferred.

consumedTime

string

Timestamp when the asset was consumed (if applicable).

issuer

string

The address of the asset issuer.

Example

import GraphQLClient from '@ocap/client';

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

(async () => {
const assetAddress = 'YOUR_ASSET_ADDRESS'; // Replace with an actual asset address
try {
const assetState = await client.getAssetState({ address: assetAddress });
console.log(`Asset State for ${assetAddress}:`);
console.log(`- Moniker: ${assetState.state.moniker}`);
console.log(`- Owner: ${assetState.state.owner}`);
console.log(`- Readonly: ${assetState.state.readonly}`);
// Output example:
// Asset State for zx...:
// - Moniker: MyNFT
// - Owner: z1...
// - Readonly: true
} catch (error) {
console.error('Error fetching asset state:', error);
}
})();

This example retrieves and displays key properties of a specific NFT.

listAssets(params)#

Lists assets (NFTs) with various filtering and pagination options.

Parameters

Name

Type

Description

paging

PageInput

Optional. Pagination parameters.

ownerAddress

string

Optional. Filter assets by owner address.

factoryAddress

string

Optional. Filter assets by the factory that minted them.

timeFilter

TimeFilterInput

Optional. Filter assets by creation time range.

Returns

Name

Type

Description

code

string

Status code of the response.

page

PageInfo

Pagination information.

assets

IndexedAssetState[]

Array of indexed asset objects.

IndexedAssetState Structure (Key Fields)

Field

Type

Description

address

string

The unique address of the asset.

owner

string

The current owner's address.

moniker

string

The name or moniker of the asset.

genesisTime

string

Timestamp when the asset was created.

Example

import GraphQLClient from '@ocap/client';

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

(async () => {
const ownerAddress = 'YOUR_OWNER_ADDRESS'; // Replace with an actual owner address
try {
const ownedAssets = await client.listAssets({
ownerAddress: ownerAddress,
paging: { size: 5, order: [{ field: 'genesisTime', type: 'DESC' }] },
});

console.log(`Latest 5 Assets owned by ${ownerAddress}:`);
ownedAssets.assets.forEach(asset => {
console.log(`- Moniker: ${asset.moniker}, Address: ${asset.address}`);
});
} catch (error) {
console.error('Error listing assets:', error);
}
})();

This example lists the 5 most recently created assets owned by a specific address.

Conclusion#

The GraphQLClient's querying capabilities provide robust tools for interacting with and extracting data from the blockchain. From general chain information to specific account and asset states, these methods are essential for building data-driven blockchain applications. You can use various filters and pagination options to tailor your queries to specific needs.

Next, explore how to modify blockchain data by sending transactions in Sending Transactions (Mutations).