@ocap/client 1.25.3 → 1.25.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +76 -80
  2. package/dist/report.html +1 -1
  3. package/docs/_sidebar.md +22 -0
  4. package/docs/api-reference-client-methods.md +229 -0
  5. package/docs/api-reference-client-methods.zh.md +229 -0
  6. package/docs/api-reference-data-types.md +482 -0
  7. package/docs/api-reference-data-types.zh.md +482 -0
  8. package/docs/api-reference-low-level-api.md +228 -0
  9. package/docs/api-reference-low-level-api.zh.md +228 -0
  10. package/docs/api-reference-query-mutation-methods.md +814 -0
  11. package/docs/api-reference-query-mutation-methods.zh.md +814 -0
  12. package/docs/api-reference-transaction-helpers.md +649 -0
  13. package/docs/api-reference-transaction-helpers.zh.md +649 -0
  14. package/docs/api-reference.md +23 -0
  15. package/docs/api-reference.zh.md +23 -0
  16. package/docs/core-concepts-client-architecture.md +102 -0
  17. package/docs/core-concepts-client-architecture.zh.md +102 -0
  18. package/docs/core-concepts-event-subscriptions.md +123 -0
  19. package/docs/core-concepts-event-subscriptions.zh.md +123 -0
  20. package/docs/core-concepts-gas-payment.md +111 -0
  21. package/docs/core-concepts-gas-payment.zh.md +111 -0
  22. package/docs/core-concepts-transaction-lifecycle.md +183 -0
  23. package/docs/core-concepts-transaction-lifecycle.zh.md +183 -0
  24. package/docs/core-concepts.md +22 -0
  25. package/docs/core-concepts.zh.md +22 -0
  26. package/docs/getting-started-basic-usage.md +87 -0
  27. package/docs/getting-started-basic-usage.zh.md +87 -0
  28. package/docs/getting-started-installation.md +60 -0
  29. package/docs/getting-started-installation.zh.md +60 -0
  30. package/docs/getting-started.md +16 -0
  31. package/docs/getting-started.zh.md +16 -0
  32. package/docs/how-to-guides-delegate-permissions.md +167 -0
  33. package/docs/how-to-guides-delegate-permissions.zh.md +167 -0
  34. package/docs/how-to-guides-manage-accounts.md +73 -0
  35. package/docs/how-to-guides-manage-accounts.zh.md +73 -0
  36. package/docs/how-to-guides-manage-assets.md +255 -0
  37. package/docs/how-to-guides-manage-assets.zh.md +255 -0
  38. package/docs/how-to-guides-manage-tokens.md +179 -0
  39. package/docs/how-to-guides-manage-tokens.zh.md +179 -0
  40. package/docs/how-to-guides-stake-tokens-and-assets.md +205 -0
  41. package/docs/how-to-guides-stake-tokens-and-assets.zh.md +205 -0
  42. package/docs/how-to-guides-transfer-tokens-and-nfts.md +179 -0
  43. package/docs/how-to-guides-transfer-tokens-and-nfts.zh.md +179 -0
  44. package/docs/how-to-guides.md +27 -0
  45. package/docs/how-to-guides.zh.md +27 -0
  46. package/docs/overview.md +70 -0
  47. package/docs/overview.zh.md +70 -0
  48. package/package.json +14 -14
package/README.md CHANGED
@@ -1,100 +1,96 @@
1
- ![graphql-client](https://www.arcblock.io/.netlify/functions/badge/?text=graphql-client)
1
+ [graphql-client]https://www.arcblock.io/.netlify/functions/badge/?text=graphql-client
2
2
 
3
- [![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier)
4
- [![docs](https://img.shields.io/badge/powered%20by-arcblock-green.svg)](https://docs.arcblock.io)
5
- [![Gitter](https://badges.gitter.im/ArcBlock/community.svg)](https://gitter.im/ArcBlock/community?utm_source=badge\&utm_medium=badge\&utm_campaign=pr-badge)
3
+ [
4
+ [
5
+ [[gitter]https://badges.gitter.im/arcblock/community.svg]https://gitter.im/arcblock/arcblock/community?utm_source = badge = badge \&utmm_medium = badge \ utm_campaign = badeaign = badeaign = badage)
6
+ 客户库可以在Node.js和浏览器环境中使用http/https通过http/https发送所有请求,将您的应用程序连接到Forge Power的区块链节点。
6
7
 
7
- Client library to connect your app with forge powered blockchain node, all requests are sent over http/https, can be used in both Node.js and browser environment.
8
+ GraphQlClient”实例主要支持5组方法,这些方法可节省您的时间,从/到区块链读取数据时。
8
9
 
9
- A `GraphQLClient` instance mainly supports 5 groups of methods that saves you time when read/write data from/to blockchain.
10
+ _`queries`:QUERY BLOCK/TRASSACTION/ACCENT/ACCENT/ASSET/CHAIN/NODE数据表格区块链
11
+ _`突变“:将事务发送到区块链``sendtx',所有交易应在发送到区块链之前签署所有交易
12
+ *``订阅':收听区块链上任何数据的更改
13
+ *``senders':采用``钱包''和`tx`对象的快捷方式,然后进行签名,然后发送
14
+ *`coders`:采用``钱包''和`tx`对象的快捷方式,编码事务以进行后期签名,内部由发件人内部使用
10
15
 
11
- * `queries`: query block/transaction/account/asset/chain/node data form the blockchain
12
- * `mutations`: send transaction to the blockchain, `sendTx`, all transactions should be signed before sending out to the blockchain
13
- * `subscriptions`: listen to changes of any data on the blockchain
14
- * `senders`: shortcut methods that takes a `wallet` and a `tx` object, then do the signing, and sending
15
- * `encoders`: shortcut methods that takes a `wallet` and a `tx` object, encode the transaction for later signing, used internally by senders
16
+ ## 目录
16
17
 
18
+ _[安装](#安装)
19
+ _[用法](#使用)
20
+ _[示例](#示例)
21
+ _[调试](#调试)\*[文档](#文档)
17
22
 
18
- ## Table of Contents
23
+ ## 安装
19
24
 
20
- * [Install](#install)
21
- * [Usage](#usage)
22
- * [Examples](#examples)
23
- * [Debugging](#debugging)
24
- * [Documentation](#documentation)
25
-
26
-
27
- ## Install
28
-
29
- ```shell
25
+ ```壳
30
26
  npm i @ocap/client -S
31
- # OR
32
- pnpm install @ocap/client
27
+ 或者
28
+ PNPM install @ocap/client
33
29
  ```
34
30
 
31
+ ## 用法
32
+
33
+ ``JS
34
+ const mcrypto = require('@ocap/mcrypto');
35
+ const graphQlclient = require('@ocap/client');
36
+ const {fromrandom,wallettype} = require('@ocap/wallet');
37
+ const {hextobytes} = require('@ocap/util');
38
+
39
+ const client = new GraphQlClient('http://localhost:8210/api');
40
+ console.log({
41
+ 查询:client.getqueries(),
42
+ 订阅:client.getSubscriptions(),
43
+ 突变:client.getmutations(),
44
+ 发件人:client.gettxsendmethods(),
45
+ 编码器:client.getTxEncodePhods(),
46
+ });
47
+
48
+ (async()=> {
49
+ //查询链状态数据
50
+ const Chaininfo =等待客户端。GetChainInfo();
51
+ const forgestate =等待客户端。
52
+ const block =等待client.getBlock({height:2});
53
+ console.log('getchaininfo',chaininfo);
54
+ console.log('getforgentate',宽恕);
55
+ console.log('getBlock',block);
56
+
57
+ //发送交易
58
+ const钱包= fromrandom(
59
+ wallettype({
60
+ 角色:mcrypto.types.roletype.role_account,
61
+ PK:mcrypto.types.keytype.secp256k1,
62
+ 哈希:mcrypto.types.hashtype.sha3,
63
+ }))
64
+ );
65
+ const hash =等待client.declare({
66
+ 绰号:“用户名”,
67
+ 钱包,
68
+ });
69
+ console.log(hash);
70
+ })();
35
71
 
36
- ## Usage
37
-
38
- ```js
39
- const Mcrypto = require('@ocap/mcrypto');
40
- const GraphQLClient = require('@ocap/client');
41
- const { fromRandom, WalletType } = require('@ocap/wallet');
42
- const { hexToBytes } = require('@ocap/util');
43
-
44
- const client = new GraphQLClient('http://localhost:8210/api');
45
- console.log({
46
- queries: client.getQueries(),
47
- subscriptions: client.getSubscriptions(),
48
- mutations: client.getMutations(),
49
- senders: client.getTxSendMethods(),
50
- encoders: client.getTxEncodeMethods(),
51
- });
52
-
53
- (async () => {
54
- // Query chain state data
55
- const chainInfo = await client.getChainInfo();
56
- const forgeState = await client.getForgeState();
57
- const block = await client.getBlock({ height: 2 });
58
- console.log('getChainInfo', chainInfo);
59
- console.log('getForgeState', forgeState);
60
- console.log('getBlock', block);
61
-
62
- // Send transaction
63
- const wallet = fromRandom(
64
- WalletType({
65
- role: Mcrypto.types.RoleType.ROLE_ACCOUNT,
66
- pk: Mcrypto.types.KeyType.SECP256K1,
67
- hash: Mcrypto.types.HashType.SHA3,
68
- })
69
- );
70
- const hash = await client.declare({
71
- moniker: 'username',
72
- wallet,
73
- });
74
- console.log(hash);
75
- })();
76
72
  ```
77
73
 
78
74
 
79
- ## Examples
75
+ ##示例
80
76
 
81
- * [Declare identify on the blockchain](./examples/declare.js)
82
- * [Get free token for newly created account](./examples/get_free_token.js)
83
- * [Transfer assets between 2 accounts](./examples/transfer_asset.js)
84
- * [Transfer tokens between 2 accounts](./examples/transfer_token.js)
85
- * [Exchange asset and token between 2 newly created accounts](./examples/exchange.js)
86
- * [Create/update asset on the blockchain](./examples/asset.js)
87
- * [Consume newly create asset](./examples/consume_asset.js)
88
- * [Stake for the connected node](./examples/stake_for_node.js)
77
+ *[在区块链上声明标识](./示例/scellare.js
78
+ *[为新创建的帐户获取免费令牌](./示例/get_free_token.js
79
+ *[2个帐户之间的转移资产](./示例/Transfer_asset.js
80
+ *[2个帐户之间的转移令牌](./示例/trassing_token.js
81
+ *[2个新创建的帐户之间的Exchange Asset和令牌](./示例/Exchange.js
82
+ *[在区块链上创建/更新资产](./示例/Asset.js
83
+ *[消费新创建资产](./示例/clummume_asset.js
84
+ *[连接节点的股份](./示例/stake_for_node.js
89
85
 
90
86
 
91
- ## Debugging
87
+ ##调试
88
+ *如果您在node.js中:`debug =@ocap/client node script.js`
89
+ *如果您在浏览器中:`localstorage.setitem('debug','@ocap/client')
92
90
 
93
- * If you are in Node.js: `DEBUG=@ocap/client node script.js`
94
- * If you are in browser: `localStorage.setItem('DEBUG', '@ocap/client')`
95
91
 
92
+ ##文档
96
93
 
97
- ## Documentation
98
-
99
- * Query arguments and response structure can be found here: [QUERIES.md](./docs/QUERIES.md)
100
- * Complete method list can be found here: [README.md](./docs/README.md)
94
+ *查询参数和响应结构可以在此处找到:[queries.md](./docs/queries.md)
95
+ *完整的方法列表可以在此处找到:[readme.md](./docs/readme.md)
96
+ ```
package/dist/report.html CHANGED
@@ -3,7 +3,7 @@
3
3
  <head>
4
4
  <meta charset="UTF-8"/>
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
6
- <title>@ocap/client [22 Sep 2025 at 12:14]</title>
6
+ <title>@ocap/client [27 Sep 2025 at 08:11]</title>
7
7
  <link rel="shortcut icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAABrVBMVEUAAAD///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////+O1foceMD///+J0/qK1Pr7/v8Xdr/9///W8P4UdL7L7P0Scr2r4Pyj3vwad8D5/f/2/f+55f3E6f34+/2H0/ojfMKpzOd0rNgQcb3F3O/j9f7c8v6g3Pz0/P/w+v/q+P7n9v6T1/uQ1vuE0vqLut/y+v+Z2fvt+f+15Pzv9fuc2/vR7v2V2Pvd6/bg9P7I6/285/2y4/yp3/zp8vk8i8kqgMT7/P31+fyv4vxGkcz6/P6/6P3j7vfS5PNnpNUxhcbO7f7F6v3O4vHK3/DA2u631Ouy0eqXweKJud5wqthfoNMMbLvY8f73+v2dxeR8sNtTmdDx9/zX6PSjyeaCtd1YnNGX2PuQveCGt95Nls42h8dLlM3F4vBtAAAAM3RSTlMAAyOx0/sKBvik8opWGBMOAe3l1snDm2E9LSb06eHcu5JpHbarfHZCN9CBb08zzkdNS0kYaptYAAAFV0lEQVRYw92X51/aYBDHHS2O2qqttVbrqNq9m+TJIAYIShBkWwqIiCgoWvfeq7Z2/s29hyQNyUcR7LveGwVyXy6XH8/9rqxglLfUPLxVduUor3h0rfp2TYvpivk37929TkG037hffoX0+peVtZQc1589rigVUdXS/ABSAyEmGIO/1XfvldSK8vs3OqB6u3m0nxmIrvgB0dj7rr7Y9IbuF68hnfFaiHA/sxqm0wciIG43P60qKv9WXWc1RXGh/mFESFABTSBi0sNAKzqet17eCtOb3kZIDwxEEU0oAIJGYxNBDhBND29e0rtXXbcpuPmED9IhEAAQ/AXEaF8EPmnrrKsv0LvWR3fg5sWDNAFZOgAgaKvZDogHNU9MFwnnYROkc56RD5CjAbQX9Ow4g7upCsvYu55aSI/Nj0H1akgKQEUM94dwK65hYRmFU9MIcH/fqJYOZYcnuJSU/waKDgTOEVaVKhwrTRP5XzgSpAITYzom7UvkhFX5VutmxeNnWDjjswTKTyfgluNDGbUpWissXhF3s7mlSml+czWkg3D0l1nNjGNjz3myOQOa1KM/jOS6ebdbAVTCi4gljHSFrviza7tOgRWcS0MOUX9zdNgag5w7rRqA44Lzw0hr1WqES36dFliSJFlh2rXIae3FFcDDgKdxrUIDePr8jGcSClV1u7A9xeN0ModY/pHMxmR1EzRh8TJiwqsHmKW0l4FCEZI+jHio+JdPPE9qwQtTRxku2D8sIeRL2LnxWSllANCQGOIiqVHAz2ye2JR0DcH+HoxDkaADLjgxjKQ+AwCX/g0+DNgdG0ukYCONAe+dbc2IAc6fwt1ARoDSezNHxV2Cmzwv3O6lDMV55edBGwGK9n1+x2F8EDfAGCxug8MhpsMEcTEAWf3rx2vZhe/LAmtIn/6apE6PN0ULKgywD9mmdxbmFl3OvD5AS5fW5zLbv/YHmcsBTjf/afDz3MaZTVCfAP9z6/Bw6ycv8EUBWJIn9zYcoAWWlW9+OzO3vkTy8H+RANLmdrpOuYWdZYEXpo+TlCJrW5EARb7fF+bWdqf3hhyZI1nWJQHgznErZhbjoEsWqi8dQNoE294aldzFurwSABL2XXMf9+H1VQGke9exw5P/AnA5Pv5ngMul7LOvO922iwACu8WkCwLCafvM4CeWPxfA8lNHcWZSoi8EwMAIciKX2Z4SWCMAa3snCZ/G4EA8D6CMLNFsGQhkkz/gQNEBbPCbWsxGUpYVu3z8IyNAknwJkfPMEhLyrdi5RTyUVACkw4GSFRNWJNEW+fgPGwHD8/JxnRuLabN4CGNRkAE23na2+VmEAUmrYymSGjMAYqH84YUIyzgzs3XC7gNgH36Vcc4zKY9o9fgPBXUAiHHwVboBHGLiX6Zcjp1f2wu4tvzZKo0ecPnDtQYDQvJXaBeNzce45Fp28ZQLrEZVuFqgBwOalArKXnW1UzlnSusQKJqKYNuz4tOnI6sZG4zanpemv+7ySU2jbA9h6uhcgpfy6G2PahirDZ6zvq6zDduMVFTKvzw8wgyEdelwY9in3XkEPs3osJuwRQ4qTkfzifndg9Gfc4pdsu82+tTnHZTBa2EAMrqr2t43pguc8tNm7JQVQ2S0ukj2d22dhXYP0/veWtwKrCkNoNimAN5+Xr/oLrxswKbVJjteWrX7eR63o4j9q0GxnaBdWgGA5VStpanIjQmEhV0/nVt5VOFUvix6awJhPcAaTEShgrG+iGyvb5a0Ndb1YGHFPEwoqAinoaykaID1o1pdPNu7XsnCKQ3R+hwWIIhGvORcJUBYXe3Xa3vq/mF/N9V13ugufMkfXn+KHsRD0B8AAAAASUVORK5CYII=" type="image/x-icon" />
8
8
 
9
9
  <script>
@@ -0,0 +1,22 @@
1
+ * [Overview](/overview.md)
2
+ * [Getting Started](/getting-started.md)
3
+ * [Installation](/getting-started-installation.md)
4
+ * [Basic Usage](/getting-started-basic-usage.md)
5
+ * [How-to Guides](/how-to-guides.md)
6
+ * [Manage Accounts](/how-to-guides-manage-accounts.md)
7
+ * [Delegate Permissions](/how-to-guides-delegate-permissions.md)
8
+ * [Transfer Tokens and NFTs](/how-to-guides-transfer-tokens-and-nfts.md)
9
+ * [Manage Assets (NFTs)](/how-to-guides-manage-assets.md)
10
+ * [Manage Tokens](/how-to-guides-manage-tokens.md)
11
+ * [Stake Tokens and Assets](/how-to-guides-stake-tokens-and-assets.md)
12
+ * [Core Concepts](/core-concepts.md)
13
+ * [Client Architecture](/core-concepts-client-architecture.md)
14
+ * [Transaction Lifecycle](/core-concepts-transaction-lifecycle.md)
15
+ * [Event Subscriptions](/core-concepts-event-subscriptions.md)
16
+ * [Gas Payment](/core-concepts-gas-payment.md)
17
+ * [API Reference](/api-reference.md)
18
+ * [Helper Methods](/api-reference-client-methods.md)
19
+ * [Query & Mutation Methods](/api-reference-query-mutation-methods.md)
20
+ * [High-level API](/api-reference-transaction-helpers.md)
21
+ * [Low-level API](/api-reference-low-level-api.md)
22
+ * [Data Types](/api-reference-data-types.md)
@@ -0,0 +1,229 @@
1
+ # Helper Methods
2
+
3
+ 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.
4
+
5
+ ```javascript Client Initialization icon=logos:javascript
6
+ const GraphQLClient = require('@ocap/client');
7
+
8
+ // Connect to the Beta chain
9
+ const client = new GraphQLClient('https://beta.abtnetwork.io/api');
10
+
11
+ (async () => {
12
+ const res = await client.getChainInfo();
13
+ console.log('Connected to chain:', res.info.network);
14
+ })();
15
+ ```
16
+
17
+ This section provides a detailed reference for the core helper methods of the `GraphQLClient` class.
18
+
19
+ ## Constructor
20
+
21
+ ### new GraphQLClient(endpoint, autoInit)
22
+
23
+ Creates a new instance of the `GraphQLClient`.
24
+
25
+ **Parameters**
26
+
27
+ <x-field-group>
28
+ <x-field data-name="endpoint" data-type="string" data-required="true">
29
+ <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>
30
+ </x-field>
31
+ <x-field data-name="autoInit" data-type="boolean" data-default="true" data-required="false">
32
+ <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>
33
+ </x-field>
34
+ </x-field-group>
35
+
36
+ **Example**
37
+
38
+ ```javascript Creating a Client Instance icon=logos:javascript
39
+ const client = new GraphQLClient('https://beta.abtnetwork.io/api', true);
40
+ ```
41
+
42
+ ---
43
+
44
+ ## Core Methods
45
+
46
+ These methods provide fundamental functionality for interacting with the client and the chain.
47
+
48
+ ### getContext()
49
+
50
+ 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.
51
+
52
+ **Returns**
53
+
54
+ <x-field data-name="Promise<object>" data-type="object" data-desc="A promise that resolves to the context object containing chain metadata.">
55
+ <x-field data-name="chainId" data-type="string" data-desc="The unique identifier of the blockchain network."></x-field>
56
+ <x-field data-name="consensus" data-type="string" data-desc="The consensus engine version."></x-field>
57
+ <x-field data-name="token" data-type="object" data-desc="Information about the native token.">
58
+ <x-field data-name="address" data-type="string" data-desc="The address of the native token contract."></x-field>
59
+ <x-field data-name="decimal" data-type="number" data-desc="The number of decimal places for the native token."></x-field>
60
+ <x-field data-name="symbol" data-type="string" data-desc="The symbol of the native token (e.g., TBA)."></x-field>
61
+ </x-field>
62
+ <x-field data-name="txConfig" data-type="object" data-desc="Transaction fee and gas configuration."></x-field>
63
+ </x-field>
64
+
65
+ **Example**
66
+
67
+ ```javascript Fetching Chain Context icon=logos:javascript
68
+ async function logChainToken() {
69
+ const context = await client.getContext();
70
+ console.log(`Native Token Symbol: ${context.token.symbol}`);
71
+ }
72
+
73
+ logChainToken();
74
+ ```
75
+
76
+ ### setGasPayer(wallet)
77
+
78
+ 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.
79
+
80
+ **Parameters**
81
+
82
+ <x-field data-name="wallet" data-type="WalletObject" data-required="true">
83
+ <x-field-desc markdown>A wallet object with `address`, `publicKey`, and `secretKey` properties, equipped with a `sign` method.</x-field-desc>
84
+ </x-field>
85
+
86
+ ### decodeTx(input)
87
+
88
+ Deserializes a transaction from various formats into a human-readable JavaScript object.
89
+
90
+ **Parameters**
91
+
92
+ <x-field data-name="input" data-type="Buffer | string" data-required="true">
93
+ <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>
94
+ </x-field>
95
+
96
+ **Returns**
97
+
98
+ <x-field data-name="object" data-type="object" data-desc="The decoded transaction object."></x-field>
99
+
100
+ ### getType(name)
101
+
102
+ 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.
103
+
104
+ **Parameters**
105
+
106
+ <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>
107
+
108
+ **Returns**
109
+
110
+ <x-field data-name="class | null" data-type="object" data-desc="The message class constructor, or null if not found."></x-field>
111
+
112
+ ---
113
+
114
+ ## Event Subscription
115
+
116
+ The client supports real-time event subscriptions over WebSockets, allowing your application to react instantly to on-chain events.
117
+
118
+ ### subscribe(topic, callback)
119
+
120
+ Establishes a WebSocket connection and subscribes to a specific event topic.
121
+
122
+ **Parameters**
123
+
124
+ <x-field-group>
125
+ <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>
126
+ <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>
127
+ </x-field-group>
128
+
129
+ ### unsubscribe(topic, callback)
130
+
131
+ Removes a previously registered callback for a specific topic.
132
+
133
+ **Parameters**
134
+
135
+ <x-field-group>
136
+ <x-field data-name="topic" data-type="string" data-required="true" data-desc="The event topic to unsubscribe from."></x-field>
137
+ <x-field data-name="callback" data-type="function" data-required="true" data-desc="The specific callback function to remove."></x-field>
138
+ </x-field-group>
139
+
140
+ **Example**
141
+
142
+ ```javascript Subscribing to New Blocks icon=logos:javascript
143
+ const handleNewBlock = (block) => {
144
+ console.log(`New block received! Height: ${block.height}`);
145
+
146
+ // Unsubscribe after receiving one block
147
+ client.unsubscribe('newBlock', handleNewBlock);
148
+ console.log('Unsubscribed from newBlock events.');
149
+ };
150
+
151
+ client.subscribe('newBlock', handleNewBlock);
152
+ console.log('Subscribed to newBlock events...');
153
+ ```
154
+
155
+ ---
156
+
157
+ ## Token Utility Methods
158
+
159
+ These helpers simplify conversions between the human-readable token amount and the on-chain base unit representation.
160
+
161
+ ### fromUnitToToken(value)
162
+
163
+ 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.
164
+
165
+ **Parameters**
166
+
167
+ <x-field data-name="value" data-type="string" data-required="true" data-desc="The amount in the chain's base unit."></x-field>
168
+
169
+ **Returns**
170
+
171
+ <x-field data-name="string" data-type="string" data-desc="The amount in the standard token unit."></x-field>
172
+
173
+ ### fromTokenToUnit(amount)
174
+
175
+ Converts a standard decimal amount into the chain's base unit representation (a BN.js instance).
176
+
177
+ **Parameters**
178
+
179
+ <x-field data-name="amount" data-type="number | string" data-required="true" data-desc="The token amount in its standard decimal form."></x-field>
180
+
181
+ **Returns**
182
+
183
+ <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>
184
+
185
+ **Example**
186
+
187
+ ```javascript Token Amount Conversion icon=logos:javascript
188
+ async function convertToken() {
189
+ // Convert 100 TBA to its base unit
190
+ const unitAmount = await client.fromTokenToUnit(100);
191
+ console.log(`100 TBA is ${unitAmount.toString()} in base units.`);
192
+
193
+ // Convert it back
194
+ const tokenAmount = await client.fromUnitToToken(unitAmount.toString());
195
+ console.log(`${unitAmount.toString()} base units is ${tokenAmount} TBA.`);
196
+ }
197
+
198
+ convertToken();
199
+ ```
200
+
201
+ ---
202
+
203
+ ## Method Discovery
204
+
205
+ 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.
206
+
207
+ ### getTxSendMethods()
208
+
209
+ Returns an array of all available `send...Tx` method names. These methods handle the full lifecycle of signing and sending a transaction.
210
+
211
+ ### getTxEncodeMethods()
212
+
213
+ 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.
214
+
215
+ ### getTxSignMethods()
216
+
217
+ Returns an array of all available `sign...Tx` method names. These methods encode and then sign a transaction, returning the signed transaction object.
218
+
219
+ ### getTxMultiSignMethods()
220
+
221
+ Returns an array of all available `multiSign...Tx` method names, used for multi-signature workflows.
222
+
223
+ **Example**
224
+
225
+ ```javascript Listing Available Transaction Methods icon=logos:javascript
226
+ const sendMethods = client.getTxSendMethods();
227
+ console.log('Available send methods:', sendMethods);
228
+ // Example output: [ 'sendPokeTx', 'sendTransferTx', ... ]
229
+ ```
@@ -0,0 +1,229 @@
1
+ # 辅助方法
2
+
3
+ `GraphQLClient` 类是与 OCAP 驱动的区块链进行交互的主要接口。它提供了一套全面的方法,用于查询链状态、发送交易以及订阅实时事件。它被设计为在 Node.js 和浏览器环境中都能无缝工作。
4
+
5
+ ```javascript 客户端初始化 icon=logos:javascript
6
+ const GraphQLClient = require('@ocap/client');
7
+
8
+ // 连接到 Beta 链
9
+ const client = new GraphQLClient('https://beta.abtnetwork.io/api');
10
+
11
+ (async () => {
12
+ const res = await client.getChainInfo();
13
+ console.log('已连接到链:', res.info.network);
14
+ })();
15
+ ```
16
+
17
+ 本节为 `GraphQLClient` 类的核心辅助方法提供了详细的参考。
18
+
19
+ ## 构造函数
20
+
21
+ ### new GraphQLClient(endpoint, autoInit)
22
+
23
+ 创建一个新的 `GraphQLClient` 实例。
24
+
25
+ **参数**
26
+
27
+ <x-field-group>
28
+ <x-field data-name="endpoint" data-type="string" data-required="true">
29
+ <x-field-desc markdown>区块链节点的 GraphQL 端点的绝对 URL(例如,`https://beta.abtnetwork.io/api`)。</x-field-desc>
30
+ </x-field>
31
+ <x-field data-name="autoInit" data-type="boolean" data-default="true" data-required="false">
32
+ <x-field-desc markdown>如果为 `true`,客户端将在初始化时自动获取并缓存基本的链信息(“上下文”)。对于大多数用例,建议使用此选项。</x-field-desc>
33
+ </x-field>
34
+ </x-field-group>
35
+
36
+ **示例**
37
+
38
+ ```javascript 创建客户端实例 icon=logos:javascript
39
+ const client = new GraphQLClient('https://beta.abtnetwork.io/api', true);
40
+ ```
41
+
42
+ ---
43
+
44
+ ## 核心方法
45
+
46
+ 这些方法提供了与客户端和链进行交互的基本功能。
47
+
48
+ ### getContext()
49
+
50
+ 获取并缓存基本的链信息,例如链 ID、原生代币详情和交易费用配置。如果在构造函数中启用了 `autoInit`,此方法会自动调用。后续调用将返回缓存的上下文。
51
+
52
+ **返回**
53
+
54
+ <x-field data-name="Promise<object>" data-type="object" data-desc="一个解析为包含链元数据的上下文对象的 promise。">
55
+ <x-field data-name="chainId" data-type="string" data-desc="区块链网络的唯一标识符。"></x-field>
56
+ <x-field data-name="consensus" data-type="string" data-desc="共识引擎版本。"></x-field>
57
+ <x-field data-name="token" data-type="object" data-desc="关于原生代币的信息。">
58
+ <x-field data-name="address" data-type="string" data-desc="原生代币合约的地址。"></x-field>
59
+ <x-field data-name="decimal" data-type="number" data-desc="原生代币的小数位数。"></x-field>
60
+ <x-field data-name="symbol" data-type="string" data-desc="原生代币的符号(例如,TBA)。"></x-field>
61
+ </x-field>
62
+ <x-field data-name="txConfig" data-type="object" data-desc="交易费用和 gas 配置。"></x-field>
63
+ </x-field>
64
+
65
+ **示例**
66
+
67
+ ```javascript 获取链上下文 icon=logos:javascript
68
+ async function logChainToken() {
69
+ const context = await client.getContext();
70
+ console.log(`原生代币符号: ${context.token.symbol}`);
71
+ }
72
+
73
+ logChainToken();
74
+ ```
75
+
76
+ ### setGasPayer(wallet)
77
+
78
+ 配置一个钱包作为“gas 支付者”。设置后,该钱包将为通过此客户端实例发送的交易赞助交易费,从而为用户提供无 gas 费体验。更多详情,请参阅 [Gas 支付](./core-concepts-gas-payment.md) 概念指南。
79
+
80
+ **参数**
81
+
82
+ <x-field data-name="wallet" data-type="WalletObject" data-required="true">
83
+ <x-field-desc markdown>一个钱包对象,具有 `address`、`publicKey` 和 `secretKey` 属性,并配备了 `sign` 方法。</x-field-desc>
84
+ </x-field>
85
+
86
+ ### decodeTx(input)
87
+
88
+ 将各种格式的交易反序列化为人类可读的 JavaScript 对象。
89
+
90
+ **参数**
91
+
92
+ <x-field data-name="input" data-type="Buffer | string" data-required="true">
93
+ <x-field-desc markdown>要解码的交易数据。可以是 `Buffer` 或 `hex`、`base58` 或 `base64` 格式的字符串。</x-field-desc>
94
+ </x-field>
95
+
96
+ **返回**
97
+
98
+ <x-field data-name="object" data-type="object" data-desc="解码后的交易对象。"></x-field>
99
+
100
+ ### getType(name)
101
+
102
+ 根据给定的类型名称检索 Protobuf 消息类。这对于需要手动构造或检查 Protobuf 消息的高级场景很有用。
103
+
104
+ **参数**
105
+
106
+ <x-field data-name="name" data-type="string" data-required="true" data-desc="Protobuf 消息类型的名称(例如,'Transaction'、'TransferTx')。"></x-field>
107
+
108
+ **返回**
109
+
110
+ <x-field data-name="class | null" data-type="object" data-desc="消息类的构造函数,如果未找到则为 null。"></x-field>
111
+
112
+ ---
113
+
114
+ ## 事件订阅
115
+
116
+ 客户端支持通过 WebSocket 进行实时事件订阅,使您的应用程序能够即时响应链上事件。
117
+
118
+ ### subscribe(topic, callback)
119
+
120
+ 建立一个 WebSocket 连接并订阅特定的事件主题。
121
+
122
+ **参数**
123
+
124
+ <x-field-group>
125
+ <x-field data-name="topic" data-type="string" data-required="true" data-desc="要订阅的事件主题(例如,'newBlock'、'tx:transfer')。"></x-field>
126
+ <x-field data-name="callback" data-type="function" data-required="true" data-desc="接收到事件时执行的函数。它接收事件负载作为其唯一参数。"></x-field>
127
+ </x-field-group>
128
+
129
+ ### unsubscribe(topic, callback)
130
+
131
+ 移除先前为特定主题注册的回调。
132
+
133
+ **参数**
134
+
135
+ <x-field-group>
136
+ <x-field data-name="topic" data-type="string" data-required="true" data-desc="要取消订阅的事件主题。"></x-field>
137
+ <x-field data-name="callback" data-type="function" data-required="true" data-desc="要移除的特定回调函数。"></x-field>
138
+ </x-field-group>
139
+
140
+ **示例**
141
+
142
+ ```javascript 订阅新区块 icon=logos:javascript
143
+ const handleNewBlock = (block) => {
144
+ console.log(`收到新区块!高度: ${block.height}`);
145
+
146
+ // 收到一个区块后取消订阅
147
+ client.unsubscribe('newBlock', handleNewBlock);
148
+ console.log('已取消订阅 newBlock 事件。');
149
+ };
150
+
151
+ client.subscribe('newBlock', handleNewBlock);
152
+ console.log('已订阅 newBlock 事件...');
153
+ ```
154
+
155
+ ---
156
+
157
+ ## 代币工具方法
158
+
159
+ 这些辅助方法简化了人类可读的代币数量和链上基本单位表示之间的转换。
160
+
161
+ ### fromUnitToToken(value)
162
+
163
+ 根据原生代币的小数位数,将一个值从链的基本单位(一个大整数字符串)转换为标准的十进制字符串。
164
+
165
+ **参数**
166
+
167
+ <x-field data-name="value" data-type="string" data-required="true" data-desc="以链的基本单位表示的数量。"></x-field>
168
+
169
+ **返回**
170
+
171
+ <x-field data-name="string" data-type="string" data-desc="以标准代币单位表示的数量。"></x-field>
172
+
173
+ ### fromTokenToUnit(amount)
174
+
175
+ 将一个标准的十进制数量转换为链的基本单位表示(一个 BN.js 实例)。
176
+
177
+ **参数**
178
+
179
+ <x-field data-name="amount" data-type="number | string" data-required="true" data-desc="以标准十进制形式表示的代币数量。"></x-field>
180
+
181
+ **返回**
182
+
183
+ <x-field data-name="BN" data-type="object" data-desc="一个 BN.js 实例,表示以链的基本单位计的值。"></x-field>
184
+
185
+ **示例**
186
+
187
+ ```javascript 代币数量转换 icon=logos:javascript
188
+ async function convertToken() {
189
+ // 将 100 TBA 转换为其基本单位
190
+ const unitAmount = await client.fromTokenToUnit(100);
191
+ console.log(`100 TBA 等于 ${unitAmount.toString()} 基本单位。`);
192
+
193
+ // 再转换回来
194
+ const tokenAmount = await client.fromUnitToToken(unitAmount.toString());
195
+ console.log(`${unitAmount.toString()} 基本单位等于 ${tokenAmount} TBA。`);
196
+ }
197
+
198
+ convertToken();
199
+ ```
200
+
201
+ ---
202
+
203
+ ## 方法发现
204
+
205
+ 客户端为所连接的 OCAP 节点支持的每种交易类型动态生成方法。这些发现方法允许您以编程方式列出所有可用的与交易相关的功能。
206
+
207
+ ### getTxSendMethods()
208
+
209
+ 返回所有可用的 `send...Tx` 方法名称的数组。这些方法处理签名和发送交易的完整生命周期。
210
+
211
+ ### getTxEncodeMethods()
212
+
213
+ 返回所有可用的 `encode...Tx` 方法名称的数组。这些方法将交易准备并序列化为缓冲区,但不进行签名。
214
+
215
+ ### getTxSignMethods()
216
+
217
+ 返回所有可用的 `sign...Tx` 方法名称的数组。这些方法对交易进行编码然后签名,返回已签名的交易对象。
218
+
219
+ ### getTxMultiSignMethods()
220
+
221
+ 返回所有可用的 `multiSign...Tx` 方法名称的数组,用于多重签名工作流。
222
+
223
+ **示例**
224
+
225
+ ```javascript 列出可用的交易方法 icon=logos:javascript
226
+ const sendMethods = client.getTxSendMethods();
227
+ console.log('可用的发送方法:', sendMethods);
228
+ // 示例输出:[ 'sendPokeTx', 'sendTransferTx', ... ]
229
+ ```