@ocap/client 1.25.3 → 1.25.5

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 (92) 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.ja.md +229 -0
  5. package/docs/api-reference-client-methods.md +229 -0
  6. package/docs/api-reference-client-methods.zh-TW.md +229 -0
  7. package/docs/api-reference-client-methods.zh.md +229 -0
  8. package/docs/api-reference-data-types.ja.md +482 -0
  9. package/docs/api-reference-data-types.md +482 -0
  10. package/docs/api-reference-data-types.zh-TW.md +482 -0
  11. package/docs/api-reference-data-types.zh.md +482 -0
  12. package/docs/api-reference-low-level-api.ja.md +228 -0
  13. package/docs/api-reference-low-level-api.md +228 -0
  14. package/docs/api-reference-low-level-api.zh-TW.md +228 -0
  15. package/docs/api-reference-low-level-api.zh.md +228 -0
  16. package/docs/api-reference-query-mutation-methods.ja.md +814 -0
  17. package/docs/api-reference-query-mutation-methods.md +814 -0
  18. package/docs/api-reference-query-mutation-methods.zh-TW.md +814 -0
  19. package/docs/api-reference-query-mutation-methods.zh.md +814 -0
  20. package/docs/api-reference-transaction-helpers.ja.md +649 -0
  21. package/docs/api-reference-transaction-helpers.md +649 -0
  22. package/docs/api-reference-transaction-helpers.zh-TW.md +649 -0
  23. package/docs/api-reference-transaction-helpers.zh.md +649 -0
  24. package/docs/api-reference.ja.md +23 -0
  25. package/docs/api-reference.md +23 -0
  26. package/docs/api-reference.zh-TW.md +23 -0
  27. package/docs/api-reference.zh.md +23 -0
  28. package/docs/core-concepts-client-architecture.ja.md +102 -0
  29. package/docs/core-concepts-client-architecture.md +102 -0
  30. package/docs/core-concepts-client-architecture.zh-TW.md +102 -0
  31. package/docs/core-concepts-client-architecture.zh.md +102 -0
  32. package/docs/core-concepts-event-subscriptions.ja.md +123 -0
  33. package/docs/core-concepts-event-subscriptions.md +123 -0
  34. package/docs/core-concepts-event-subscriptions.zh-TW.md +123 -0
  35. package/docs/core-concepts-event-subscriptions.zh.md +123 -0
  36. package/docs/core-concepts-gas-payment.ja.md +111 -0
  37. package/docs/core-concepts-gas-payment.md +111 -0
  38. package/docs/core-concepts-gas-payment.zh-TW.md +111 -0
  39. package/docs/core-concepts-gas-payment.zh.md +111 -0
  40. package/docs/core-concepts-transaction-lifecycle.ja.md +183 -0
  41. package/docs/core-concepts-transaction-lifecycle.md +183 -0
  42. package/docs/core-concepts-transaction-lifecycle.zh-TW.md +183 -0
  43. package/docs/core-concepts-transaction-lifecycle.zh.md +183 -0
  44. package/docs/core-concepts.ja.md +22 -0
  45. package/docs/core-concepts.md +22 -0
  46. package/docs/core-concepts.zh-TW.md +22 -0
  47. package/docs/core-concepts.zh.md +22 -0
  48. package/docs/getting-started-basic-usage.ja.md +87 -0
  49. package/docs/getting-started-basic-usage.md +87 -0
  50. package/docs/getting-started-basic-usage.zh-TW.md +87 -0
  51. package/docs/getting-started-basic-usage.zh.md +87 -0
  52. package/docs/getting-started-installation.ja.md +60 -0
  53. package/docs/getting-started-installation.md +60 -0
  54. package/docs/getting-started-installation.zh-TW.md +60 -0
  55. package/docs/getting-started-installation.zh.md +60 -0
  56. package/docs/getting-started.ja.md +16 -0
  57. package/docs/getting-started.md +16 -0
  58. package/docs/getting-started.zh-TW.md +16 -0
  59. package/docs/getting-started.zh.md +17 -0
  60. package/docs/how-to-guides-delegate-permissions.ja.md +167 -0
  61. package/docs/how-to-guides-delegate-permissions.md +167 -0
  62. package/docs/how-to-guides-delegate-permissions.zh-TW.md +167 -0
  63. package/docs/how-to-guides-delegate-permissions.zh.md +166 -0
  64. package/docs/how-to-guides-manage-accounts.ja.md +73 -0
  65. package/docs/how-to-guides-manage-accounts.md +73 -0
  66. package/docs/how-to-guides-manage-accounts.zh-TW.md +73 -0
  67. package/docs/how-to-guides-manage-accounts.zh.md +73 -0
  68. package/docs/how-to-guides-manage-assets.ja.md +255 -0
  69. package/docs/how-to-guides-manage-assets.md +255 -0
  70. package/docs/how-to-guides-manage-assets.zh-TW.md +255 -0
  71. package/docs/how-to-guides-manage-assets.zh.md +255 -0
  72. package/docs/how-to-guides-manage-tokens.ja.md +179 -0
  73. package/docs/how-to-guides-manage-tokens.md +179 -0
  74. package/docs/how-to-guides-manage-tokens.zh-TW.md +179 -0
  75. package/docs/how-to-guides-manage-tokens.zh.md +179 -0
  76. package/docs/how-to-guides-stake-tokens-and-assets.ja.md +205 -0
  77. package/docs/how-to-guides-stake-tokens-and-assets.md +205 -0
  78. package/docs/how-to-guides-stake-tokens-and-assets.zh-TW.md +205 -0
  79. package/docs/how-to-guides-stake-tokens-and-assets.zh.md +205 -0
  80. package/docs/how-to-guides-transfer-tokens-and-nfts.ja.md +179 -0
  81. package/docs/how-to-guides-transfer-tokens-and-nfts.md +179 -0
  82. package/docs/how-to-guides-transfer-tokens-and-nfts.zh-TW.md +179 -0
  83. package/docs/how-to-guides-transfer-tokens-and-nfts.zh.md +179 -0
  84. package/docs/how-to-guides.ja.md +27 -0
  85. package/docs/how-to-guides.md +27 -0
  86. package/docs/how-to-guides.zh-TW.md +27 -0
  87. package/docs/how-to-guides.zh.md +27 -0
  88. package/docs/overview.ja.md +70 -0
  89. package/docs/overview.md +70 -0
  90. package/docs/overview.zh-TW.md +70 -0
  91. package/docs/overview.zh.md +70 -0
  92. package/package.json +14 -14
@@ -0,0 +1,123 @@
1
+ # Event Subscriptions
2
+
3
+ The OCAP Client provides a powerful, real-time event subscription system that allows your application to listen for on-chain activities as they happen. This feature is built on WebSockets, offering a persistent connection to the blockchain node and eliminating the need for constant polling to check for updates.
4
+
5
+ By subscribing to specific event topics, you can receive instant notifications for a wide range of on-chain events, such as when a new transaction is created, an asset is transferred, or a token is exchanged. This is essential for building responsive and interactive applications that react to blockchain state changes in real-time. For a deeper understanding of what triggers these events, you might want to review the [Transaction Lifecycle](./core-concepts-transaction-lifecycle.md).
6
+
7
+ ## How It Works
8
+
9
+ Under the hood, when you first subscribe to an event, the OCAP Client automatically establishes a WebSocket connection to the designated endpoint of the blockchain node. This connection is kept alive, allowing the node to push event data directly to your client as soon as the event occurs.
10
+
11
+ The client manages the WebSocket connection lifecycle for you. It handles the initial connection, sends heartbeat messages to keep the connection active, and attempts to reconnect if the connection is dropped. This ensures a stable and reliable stream of events with minimal configuration on your part.
12
+
13
+ ## Subscribing to Events
14
+
15
+ To start listening for events, you use the `subscribe` method. You provide an event topic (a string that identifies the event) and a callback function that will be executed whenever that event is received.
16
+
17
+ ```javascript OCAP Client icon=logos:javascript
18
+ const client = new GraphQLClient('https://beta.abtnetwork.io/api/v2/gql');
19
+
20
+ const handleNewTransaction = (eventData) => {
21
+ console.log('A new transaction was created on-chain:', eventData);
22
+ };
23
+
24
+ // Subscribe to the 'tx.create' topic
25
+ client.subscribe('tx.create', handleNewTransaction);
26
+ ```
27
+
28
+ ### Method Signature
29
+
30
+ **`subscribe(topic, callback)`**
31
+
32
+ <x-field-group>
33
+ <x-field data-name="topic" data-type="string" data-required="true" data-desc="The name of the event topic to subscribe to. For example, 'tx.create'."></x-field>
34
+ <x-field data-name="callback" data-type="Function" data-required="true" data-desc="The function to execute when an event is received. The event data is passed as the first argument."></x-field>
35
+ </x-field-group>
36
+
37
+ ### Common Event Topics
38
+
39
+ Event topics generally follow the pattern `tx.<transaction_type>`. Here are some common examples:
40
+
41
+ | Topic | Description |
42
+ |---|---|
43
+ | `tx.create` | Fired when any new transaction is successfully processed and added to a block. |
44
+ | `tx.transfer_v2` | Fired specifically when a `transferV2` transaction occurs. |
45
+ | `tx.exchange_v2` | Fired when an `exchangeV2` (atomic swap) transaction is completed. |
46
+ | `tx.create_asset` | Fired when a new asset (NFT) is created. |
47
+
48
+ ## Unsubscribing from Events
49
+
50
+ It's good practice to clean up your subscriptions when they are no longer needed, especially in single-page applications where components mount and unmount. This prevents memory leaks and unnecessary processing. You can remove a subscription using the `unsubscribe` method.
51
+
52
+ ```javascript OCAP Client icon=logos:javascript
53
+ // To remove a specific listener, pass the same callback function reference
54
+ client.unsubscribe('tx.create', handleNewTransaction);
55
+
56
+ // To remove all listeners for a specific topic
57
+ client.unsubscribe('tx.create');
58
+ ```
59
+
60
+ ### Method Signature
61
+
62
+ **`unsubscribe(topic, [callback])`**
63
+
64
+ <x-field-group>
65
+ <x-field data-name="topic" data-type="string" data-required="true" data-desc="The name of the event topic to unsubscribe from."></x-field>
66
+ <x-field data-name="callback" data-type="Function" data-required="false" data-desc="Optional. The specific callback function to remove. If omitted, all listeners for the given topic will be removed."></x-field>
67
+ </x-field-group>
68
+
69
+ ## Complete Example
70
+
71
+ Here is a complete example that demonstrates subscribing to an event, triggering it, and then unsubscribing.
72
+
73
+ ```javascript Event Subscription Lifecycle icon=logos:javascript
74
+ import GraphQLClient from '@ocap/client';
75
+ import { fromRandom } from '@ocap/wallet';
76
+
77
+ const main = async () => {
78
+ const client = new GraphQLClient('https://beta.abtnetwork.io/api/v2/gql');
79
+ const events = { txCreate: 0, txTransfer: 0 };
80
+
81
+ // 1. Subscribe to events
82
+ client.subscribe('tx.create', () => (events.txCreate += 1));
83
+ client.subscribe('tx.transfer_v2', () => (events.txTransfer += 1));
84
+
85
+ console.log('Subscribed to tx.create and tx.transfer_v2 events...');
86
+
87
+ // Helper to wait for a short period
88
+ const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
89
+ await sleep(100); // Wait a moment for the subscription to register
90
+
91
+ // 2. Perform an action that triggers the events
92
+ // Note: This requires a wallet with funds. You can get test tokens from https://faucet.abtnetwork.io/
93
+ const sender = fromRandom(); // In a real app, load a funded wallet
94
+ // For this example, we'll assume the action would succeed.
95
+ console.log('A transfer transaction would trigger the event handlers.');
96
+
97
+ // In a real scenario, after a successful transfer:
98
+ // await client.transfer({ to: 'z1...', token: 1, wallet: sender });
99
+
100
+ // Let's simulate the event counters being incremented after a successful transaction
101
+ events.txCreate = 1;
102
+ events.txTransfer = 1;
103
+
104
+ await sleep(100); // Wait for events to be processed
105
+
106
+ // 3. Verify that the event handlers were called
107
+ console.log(`tx.create was called ${events.txCreate} time(s).`);
108
+ console.log(`tx.transfer_v2 was called ${events.txTransfer} time(s).`);
109
+
110
+ // 4. Unsubscribe to clean up
111
+ client.unsubscribe('tx.create');
112
+ client.unsubscribe('tx.transfer_v2');
113
+ console.log('Unsubscribed from events.');
114
+ };
115
+
116
+ main().catch(console.error);
117
+ ```
118
+
119
+ ## Summary
120
+
121
+ Event subscriptions are a core feature for building dynamic dApps with the OCAP Client. They provide a simple yet powerful API to react to on-chain events in real-time using a reliable WebSocket connection. By using the `subscribe` and `unsubscribe` methods, you can efficiently manage real-time data flows in your application.
122
+
123
+ For more details on how transactions are constructed and sent, which in turn generate these events, see the [Transaction Lifecycle](./core-concepts-transaction-lifecycle.md) documentation. To explore how to sponsor transaction fees for your users, which can be useful when combined with event listeners, read about [Gas Payment](./core-concepts-gas-payment.md).
@@ -0,0 +1,123 @@
1
+ # 事件訂閱
2
+
3
+ OCAP Client 提供了一個功能強大的即時事件訂閱系統,讓您的應用程式能夠在鏈上活動發生時即時監聽。此功能基於 WebSockets 建立,提供與區塊鏈節點的持久連接,無需透過持續輪詢來檢查更新。
4
+
5
+ 透過訂閱特定的事件主題,您可以即時收到各種鏈上事件的通知,例如新交易的建立、資產的轉移或代幣的交換。這對於建立能即時回應區塊鏈狀態變化的響應式和互動式應用程式至關重要。若想更深入了解觸發這些事件的原因,您可以參閱 [交易生命週期](./core-concepts-transaction-lifecycle.md)。
6
+
7
+ ## 運作原理
8
+
9
+ 在底層,當您首次訂閱事件時,OCAP Client 會自動與區塊鏈節點的指定端點建立 WebSocket 連接。此連接會保持活動狀態,讓節點能在事件發生時立即將事件資料推送到您的客戶端。
10
+
11
+ 客戶端會為您管理 WebSocket 的連接生命週期,包括處理初始連接、發送心跳訊息以維持連接,以及在連接中斷時嘗試重新連接。這確保了您只需進行最少的設定,就能獲得穩定可靠的事件流。
12
+
13
+ ## 訂閱事件
14
+
15
+ 若要開始監聽事件,請使用 `subscribe` 方法。您需要提供一個事件主題(用來識別事件的字串)和一個回呼函式,每當收到該事件時,此函式便會執行。
16
+
17
+ ```javascript OCAP Client icon=logos:javascript
18
+ const client = new GraphQLClient('https://beta.abtnetwork.io/api/v2/gql');
19
+
20
+ const handleNewTransaction = (eventData) => {
21
+ console.log('A new transaction was created on-chain:', eventData);
22
+ };
23
+
24
+ // Subscribe to the 'tx.create' topic
25
+ client.subscribe('tx.create', handleNewTransaction);
26
+ ```
27
+
28
+ ### 方法簽名
29
+
30
+ **`subscribe(topic, callback)`**
31
+
32
+ <x-field-group>
33
+ <x-field data-name="topic" data-type="string" data-required="true" data-desc="要訂閱的事件主題名稱。例如:'tx.create'。"></x-field>
34
+ <x-field data-name="callback" data-type="Function" data-required="true" data-desc="收到事件時要執行的函式。事件資料會作為第一個參數傳入。"></x-field>
35
+ </x-field-group>
36
+
37
+ ### 常見事件主題
38
+
39
+ 事件主題通常遵循 `tx.<transaction_type>` 的格式。以下是一些常見範例:
40
+
41
+ | Topic | Description |
42
+ |---|---|
43
+ | `tx.create` | 當任何新交易成功處理並加入區塊時觸發。 |
44
+ | `tx.transfer_v2` | 當 `transferV2` 交易發生時觸發。 |
45
+ | `tx.exchange_v2` | 當 `exchangeV2`(原子交換)交易完成時觸發。 |
46
+ | `tx.create_asset` | 當新資產(NFT)被建立時觸發。 |
47
+
48
+ ## 取消訂閱事件
49
+
50
+ 當不再需要訂閱時,最好將其清除,尤其是在元件會掛載和卸載的單頁應用程式中。這樣可以防止記憶體洩漏和不必要的處理。您可以使用 `unsubscribe` 方法來移除訂閱。
51
+
52
+ ```javascript OCAP Client icon=logos:javascript
53
+ // 若要移除特定的監聽器,請傳入相同的回呼函式參考
54
+ client.unsubscribe('tx.create', handleNewTransaction);
55
+
56
+ // 若要移除特定主題的所有監聽器
57
+ client.unsubscribe('tx.create');
58
+ ```
59
+
60
+ ### 方法簽名
61
+
62
+ **`unsubscribe(topic, [callback])`**
63
+
64
+ <x-field-group>
65
+ <x-field data-name="topic" data-type="string" data-required="true" data-desc="要取消訂閱的事件主題名稱。"></x-field>
66
+ <x-field data-name="callback" data-type="Function" data-required="false" data-desc="選填。要移除的特定回呼函式。如果省略,該主題的所有監聽器都將被移除。"></x-field>
67
+ </x-field-group>
68
+
69
+ ## 完整範例
70
+
71
+ 以下是一個完整範例,示範了如何訂閱事件、觸發事件,然後取消訂閱。
72
+
73
+ ```javascript Event Subscription Lifecycle icon=logos:javascript
74
+ import GraphQLClient from '@ocap/client';
75
+ import { fromRandom } from '@ocap/wallet';
76
+
77
+ const main = async () => {
78
+ const client = new GraphQLClient('https://beta.abtnetwork.io/api/v2/gql');
79
+ const events = { txCreate: 0, txTransfer: 0 };
80
+
81
+ // 1. 訂閱事件
82
+ client.subscribe('tx.create', () => (events.txCreate += 1));
83
+ client.subscribe('tx.transfer_v2', () => (events.txTransfer += 1));
84
+
85
+ console.log('Subscribed to tx.create and tx.transfer_v2 events...');
86
+
87
+ // 輔助函式,用於等待一小段時間
88
+ const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
89
+ await sleep(100); // 稍待片刻,讓訂閱註冊成功
90
+
91
+ // 2. 執行一個會觸發事件的動作
92
+ // 注意:這需要一個有資金的錢包。您可以從 https://faucet.abtnetwork.io/ 獲取測試代幣
93
+ const sender = fromRandom(); // 在實際應用中,請載入一個有資金的錢包
94
+ // 在此範例中,我們假設該動作會成功。
95
+ console.log('A transfer transaction would trigger the event handlers.');
96
+
97
+ // 在真實情境中,成功轉帳後:
98
+ // await client.transfer({ to: 'z1...', token: 1, wallet: sender });
99
+
100
+ // 讓我們模擬成功交易後事件計數器增加的情況
101
+ events.txCreate = 1;
102
+ events.txTransfer = 1;
103
+
104
+ await sleep(100); // 等待事件處理完成
105
+
106
+ // 3. 驗證事件處理器是否被呼叫
107
+ console.log(`tx.create was called ${events.txCreate} time(s).`);
108
+ console.log(`tx.transfer_v2 was called ${events.txTransfer} time(s).`);
109
+
110
+ // 4. 取消訂閱以進行清理
111
+ client.unsubscribe('tx.create');
112
+ client.unsubscribe('tx.transfer_v2');
113
+ console.log('Unsubscribed from events.');
114
+ };
115
+
116
+ main().catch(console.error);
117
+ ```
118
+
119
+ ## 總結
120
+
121
+ 事件訂閱是使用 OCAP Client 建立動態 dApp 的核心功能。它提供了一個簡單而強大的 API,可透過可靠的 WebSocket 連接即時回應鏈上事件。透過使用 `subscribe` 和 `unsubscribe` 方法,您可以有效管理應用程式中的即時資料流。
122
+
123
+ 關於如何建構和發送交易(進而產生這些事件)的更多詳細資訊,請參閱 [交易生命週期](./core-concepts-transaction-lifecycle.md) 文件。若要了解如何為使用者贊助交易費用(這在與事件監聽器結合使用時非常有用),請閱讀關於 [Gas 支付](./core-concepts-gas-payment.md) 的內容。
@@ -0,0 +1,123 @@
1
+ # 事件订阅
2
+
3
+ OCAP Client 提供了一个强大的实时事件订阅系统,允许您的应用程序在链上活动发生时进行监听。该功能基于 WebSocket 构建,提供与区块链节点的持久连接,无需通过持续轮询来检查更新。
4
+
5
+ 通过订阅特定的事件主题,您可以接收各种链上事件的即时通知,例如当新交易创建、资产转移或代币交换时。这对于构建能够实时响应区块链状态变化的响应式和交互式应用程序至关重要。要更深入地了解触发这些事件的原因,您可能需要查阅[交易生命周期](./core-concepts-transaction-lifecycle.md)。
6
+
7
+ ## 工作原理
8
+
9
+ 在底层,当您首次订阅事件时,OCAP Client 会自动与区块链节点的指定端点建立 WebSocket 连接。此连接将保持活动状态,允许节点在事件发生时立即将事件数据推送至您的客户端。
10
+
11
+ 客户端为您管理 WebSocket 连接的生命周期。它处理初始连接,发送心跳消息以保持连接活跃,并在连接断开时尝试重新连接。这确保了事件流的稳定和可靠,而您只需进行最少的配置。
12
+
13
+ ## 订阅事件
14
+
15
+ 要开始监听事件,您可以使用 `subscribe` 方法。您需要提供一个事件主题(标识事件的字符串)和一个回调函数,该函数将在收到事件时执行。
16
+
17
+ ```javascript OCAP Client icon=logos:javascript
18
+ const client = new GraphQLClient('https://beta.abtnetwork.io/api/v2/gql');
19
+
20
+ const handleNewTransaction = (eventData) => {
21
+ console.log('A new transaction was created on-chain:', eventData);
22
+ };
23
+
24
+ // 订阅 'tx.create' 主题
25
+ client.subscribe('tx.create', handleNewTransaction);
26
+ ```
27
+
28
+ ### 方法签名
29
+
30
+ **`subscribe(topic, callback)`**
31
+
32
+ <x-field-group>
33
+ <x-field data-name="topic" data-type="string" data-required="true" data-desc="要订阅的事件主题的名称。例如,'tx.create'。"></x-field>
34
+ <x-field data-name="callback" data-type="Function" data-required="true" data-desc="接收到事件时要执行的函数。事件数据作为第一个参数传递。"></x-field>
35
+ </x-field-group>
36
+
37
+ ### 常见事件主题
38
+
39
+ 事件主题通常遵循 `tx.<transaction_type>` 的模式。以下是一些常见示例:
40
+
41
+ | Topic | Description |
42
+ |---|---|
43
+ | `tx.create` | 当任何新交易成功处理并被添加到区块中时触发。 |
44
+ | `tx.transfer_v2` | 当 `transferV2` 交易发生时专门触发。 |
45
+ | `tx.exchange_v2` | 当 `exchangeV2`(原子交换)交易完成时触发。 |
46
+ | `tx.create_asset` | 当新资产(NFT)被创建时触发。 |
47
+
48
+ ## 取消订阅事件
49
+
50
+ 在不再需要订阅时进行清理是一个好习惯,特别是在组件会挂载和卸载的单页应用程序中。这可以防止内存泄漏和不必要的处理。您可以使用 `unsubscribe` 方法来移除订阅。
51
+
52
+ ```javascript OCAP Client icon=logos:javascript
53
+ // 要移除特定的监听器,请传递相同的回调函数引用
54
+ client.unsubscribe('tx.create', handleNewTransaction);
55
+
56
+ // 要移除特定主题的所有监听器
57
+ client.unsubscribe('tx.create');
58
+ ```
59
+
60
+ ### 方法签名
61
+
62
+ **`unsubscribe(topic, [callback])`**
63
+
64
+ <x-field-group>
65
+ <x-field data-name="topic" data-type="string" data-required="true" data-desc="要取消订阅的事件主题的名称。"></x-field>
66
+ <x-field data-name="callback" data-type="Function" data-required="false" data-desc="可选。要移除的特定回调函数。如果省略,将移除该主题的所有监听器。"></x-field>
67
+ </x-field-group>
68
+
69
+ ## 完整示例
70
+
71
+ 以下是一个完整的示例,演示了订阅事件、触发事件然后取消订阅的过程。
72
+
73
+ ```javascript Event Subscription Lifecycle icon=logos:javascript
74
+ import GraphQLClient from '@ocap/client';
75
+ import { fromRandom } from '@ocap/wallet';
76
+
77
+ const main = async () => {
78
+ const client = new GraphQLClient('https://beta.abtnetwork.io/api/v2/gql');
79
+ const events = { txCreate: 0, txTransfer: 0 };
80
+
81
+ // 1. 订阅事件
82
+ client.subscribe('tx.create', () => (events.txCreate += 1));
83
+ client.subscribe('tx.transfer_v2', () => (events.txTransfer += 1));
84
+
85
+ console.log('已订阅 tx.create 和 tx.transfer_v2 事件...');
86
+
87
+ // 等待一小段时间的辅助函数
88
+ const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
89
+ await sleep(100); // 等待片刻以注册订阅
90
+
91
+ // 2. 执行触发事件的操作
92
+ // 注意:这需要一个有资金的钱包。您可以从 https://faucet.abtnetwork.io/ 获取测试代币。
93
+ const sender = fromRandom(); // 在真实应用中,加载一个有资金的钱包
94
+ // 在此示例中,我们假设操作会成功。
95
+ console.log('一笔转账交易将触发事件处理程序。');
96
+
97
+ // 在真实场景中,成功转账后:
98
+ // await client.transfer({ to: 'z1...', token: 1, wallet: sender });
99
+
100
+ // 让我们模拟在成功交易后事件计数器递增
101
+ events.txCreate = 1;
102
+ events.txTransfer = 1;
103
+
104
+ await sleep(100); // 等待事件处理
105
+
106
+ // 3. 验证事件处理程序是否被调用
107
+ console.log(`tx.create 被调用了 ${events.txCreate} 次。`);
108
+ console.log(`tx.transfer_v2 被调用了 ${events.txTransfer} 次。`);
109
+
110
+ // 4. 取消订阅以进行清理
111
+ client.unsubscribe('tx.create');
112
+ client.unsubscribe('tx.transfer_v2');
113
+ console.log('已取消事件订阅。');
114
+ };
115
+
116
+ main().catch(console.error);
117
+ ```
118
+
119
+ ## 总结
120
+
121
+ 事件订阅是使用 OCAP Client 构建动态 dApp 的核心功能。它们提供了一个简单而强大的 API,通过可靠的 WebSocket 连接实时响应链上事件。通过使用 `subscribe` 和 `unsubscribe` 方法,您可以有效地管理应用程序中的实时数据流。
122
+
123
+ 有关如何构建和发送交易(这些交易会生成这些事件)的更多详细信息,请参阅[交易生命周期](./core-concepts-transaction-lifecycle.md)文档。要了解如何为您的用户赞助交易费用(这在与事件监听器结合使用时非常有用),请阅读[燃料费支付](./core-concepts-gas-payment.md)。
@@ -0,0 +1,111 @@
1
+ # Gas支払い
2
+
3
+ ほとんどのブロックチェーンシステムでは、すべてのトランザクションには、一般的に「ガス」として知られる手数料が必要であり、これは発信者が支払う必要があります。これは、これらの手数料を支払うためのネイティブ通貨を持っていない新規ユーザーにとっては、大きな障壁となり得ます。OCAP Clientは、アプリケーション開発者がこれらの手数料をスポンサーできるGas支払い機能を導入し、ユーザーにシームレスな「ガスレス」体験を提供します。
4
+
5
+ この強力な機能により、dAppsはガスの複雑さを抽象化し、ユーザーのオンボーディングとアプリケーション全体のユーザビリティを向上させることができます。
6
+
7
+ ## 仕組み
8
+
9
+ ガス支払いメカニズムは、標準のHTTPヘッダーを介して実装されます。クライアントインスタンスにガス支払いウォレットを設定すると、クライアントはブロックチェーンノードに送信するすべての `sendTx` ミューテーションに、2つの特別なヘッダーを自動的に添付します:
10
+
11
+ - `x-gas-payer-pk`: ガス料金を支払うウォレットの公開鍵。
12
+ - `x-gas-payer-sig`: ガス支払い者の秘密鍵で署名されたJSON Web Token (JWT)。このトークンにはトランザクションのハッシュが含まれており、その特定のトランザクションの手数料を支払うためのスポンサーからの検証可能な承認として機能します。
13
+
14
+ ブロックチェーンノードがトランザクションを受信すると、2つの重要な検証を実行します:
15
+
16
+ 1. トランザクション自体のユーザーの署名を検証します。
17
+ 2. ヘッダー内のガス支払い者の署名をトランザクションハッシュと照合して検証します。
18
+
19
+ 両方の署名が有効な場合、トランザクションはユーザーの権限で実行されますが、対応するガス料金はガス支払い者のアカウント残高から差し引かれます。
20
+
21
+ ### ワークフロー図
22
+
23
+ 以下の図は、トランザクションの開始から実行までのガス支払いフロー全体を示しています:
24
+
25
+ ```d2 ガス支払いのワークフロー icon=mdi:gas-station
26
+ direction: down
27
+
28
+ User-App: {
29
+ label: "ユーザーのアプリケーション"
30
+ shape: rectangle
31
+ }
32
+
33
+ Gas-Payer-Wallet: {
34
+ label: "ガス支払いウォレット\n(アプリバックエンドのウォレット)"
35
+ shape: cylinder
36
+ }
37
+
38
+ OCAP-Client: {
39
+ label: "OCAPクライアントインスタンス"
40
+ }
41
+
42
+ Blockchain-Node: {
43
+ label: "ブロックチェーンノード"
44
+ shape: rectangle
45
+ }
46
+
47
+ User-App -> OCAP-Client: "1. ユーザーがトランザクションを開始"
48
+ OCAP-Client -> OCAP-Client: "2. ユーザーのウォレットで\nTxを準備・署名"
49
+ Gas-Payer-Wallet -> OCAP-Client: "3. ガスのためにTxハッシュに署名"
50
+ OCAP-Client -> Blockchain-Node: "4. Tx + ガス支払いヘッダーを送信"
51
+ Blockchain-Node -> Blockchain-Node: "5. 両方の署名を検証"
52
+ Blockchain-Node: "6. トランザクションを実行"
53
+ Blockchain-Node -> Gas-Payer-Wallet: "7. ガス料金を差し引く"
54
+ ```
55
+
56
+ ## 使用例
57
+
58
+ ガスレストランザクションを有効にするには、スポンサーアカウント用のウォレットインスタンスを作成し、`setGasPayer` メソッドを使用してクライアントに設定するだけです。
59
+
60
+ ```javascript Gas Payer Setup and Usage icon=logos:javascript
61
+ import Client from '@ocap/client';
62
+ import Wallet, { fromRandom } from '@ocap/wallet';
63
+
64
+ // 1. Betaチェーンに接続するためにクライアントを初期化します
65
+ const client = new Client('https://beta.abtnetwork.io/api');
66
+
67
+ // 2. ガス支払い者(アプリケーションのウォレット)用のウォレットを作成します
68
+ // このウォレットには、トランザクション手数料をカバーするのに十分なネイティブトークン(TBA)が必要です。
69
+ // テストトークンはフォーセットから入手できます: https://faucet.abtnetwork.io/
70
+ const gasPayerWallet = Wallet.fromJSON({
71
+ sk: '...your_sponsor_secret_key...',
72
+ pk: '...your_sponsor_public_key...',
73
+ address: '...your_sponsor_address...',
74
+ });
75
+
76
+ // 3. クライアントインスタンスにガス支払い者を設定します
77
+ client.setGasPayer(gasPayerWallet);
78
+
79
+ // 4. エンドユーザー用のウォレットを作成します。
80
+ const userWallet = fromRandom();
81
+
82
+ // 5. ユーザーのウォレットを使用してトランザクションを送信します。
83
+ // トランザクションはユーザーによって署名されますが、ガス料金はgasPayerWalletによって支払われます。
84
+ async function performGaslessTransaction() {
85
+ try {
86
+ // 注:新しいアカウントは最初の受信トランザクションでオンチェーンに作成されますが、
87
+ // トランザクションを *送信* する前にオンチェーンに存在している必要があります。
88
+ // フォーセットから少量のトークンを送信することで初期化できます。
89
+
90
+ const receiverAddress = 'z1...'; // 有効な受信者アドレス
91
+ const hash = await client.transfer({
92
+ to: receiverAddress,
93
+ tokens: [{ value: '0.1' }], // 0.1 TBAを送信
94
+ wallet: userWallet,
95
+ });
96
+
97
+ console.log('ガスレストランザクション成功。ハッシュ:', hash);
98
+ console.log(`エクスプローラーで確認: https://beta.abtnetwork.io/explorer/txs/${hash}`);
99
+ } catch (error) {
100
+ console.error('トランザクション失敗:', error);
101
+ }
102
+ }
103
+
104
+ performGaslessTransaction();
105
+ ```
106
+
107
+ この例では、`gasPayerWallet`がコストを負担するため、`userWallet`はネイティブトークンの残高がゼロであってもトランザクションを正常に送信できます。これにより、特にアプリケーションに参加する新規ユーザーにとって、摩擦のない体験が生まれます。
108
+
109
+ ---
110
+
111
+ トランザクションの作成から確定までの全行程を理解するには、[トランザクションライフサイクル](./core-concepts-transaction-lifecycle.md)のドキュメントを参照してください。
@@ -0,0 +1,111 @@
1
+ # Gas Payment
2
+
3
+ In most blockchain systems, every transaction requires a fee, commonly known as "gas," to be paid by the initiator. This can be a significant hurdle for new users who may not have the native currency to pay these fees. The OCAP Client introduces a Gas Payment feature that allows application developers to sponsor these fees, creating a seamless, "gasless" experience for their users.
4
+
5
+ This powerful feature enables dApps to abstract away the complexity of gas, improving user onboarding and overall application usability.
6
+
7
+ ## How It Works
8
+
9
+ The gas payment mechanism is implemented through standard HTTP headers. When you configure a gas payer wallet on your client instance, the client automatically attaches two special headers to every `sendTx` mutation it sends to the blockchain node:
10
+
11
+ - `x-gas-payer-pk`: The public key of the wallet that will pay the gas fee.
12
+ - `x-gas-payer-sig`: A JSON Web Token (JWT) signed by the gas payer's secret key. This token contains the hash of the transaction, acting as a verifiable authorization from the sponsor to pay the fee for that specific transaction.
13
+
14
+ When the blockchain node receives the transaction, it performs two critical validations:
15
+
16
+ 1. It verifies the user's signature on the transaction itself.
17
+ 2. It verifies the gas payer's signature in the header against the transaction hash.
18
+
19
+ If both signatures are valid, the transaction is executed under the user's authority, but the corresponding gas fee is deducted from the gas payer's account balance.
20
+
21
+ ### Workflow Diagram
22
+
23
+ The following diagram illustrates the entire gas payment flow from transaction initiation to execution:
24
+
25
+ ```d2 The Gas Payment Workflow icon=mdi:gas-station
26
+ direction: down
27
+
28
+ User-App: {
29
+ label: "User's Application"
30
+ shape: rectangle
31
+ }
32
+
33
+ Gas-Payer-Wallet: {
34
+ label: "Gas Payer Wallet\n(App Backend's Wallet)"
35
+ shape: cylinder
36
+ }
37
+
38
+ OCAP-Client: {
39
+ label: "OCAP Client Instance"
40
+ }
41
+
42
+ Blockchain-Node: {
43
+ label: "Blockchain Node"
44
+ shape: rectangle
45
+ }
46
+
47
+ User-App -> OCAP-Client: "1. User initiates transaction"
48
+ OCAP-Client -> OCAP-Client: "2. Prepare & sign Tx with\nuser's wallet"
49
+ Gas-Payer-Wallet -> OCAP-Client: "3. Sign Tx hash for gas"
50
+ OCAP-Client -> Blockchain-Node: "4. Send Tx + Gas Payer headers"
51
+ Blockchain-Node -> Blockchain-Node: "5. Verify both signatures"
52
+ Blockchain-Node: "6. Execute transaction"
53
+ Blockchain-Node -> Gas-Payer-Wallet: "7. Deduct gas fee"
54
+ ```
55
+
56
+ ## Usage Example
57
+
58
+ To enable gasless transactions, you simply need to create a wallet instance for the sponsoring account and set it on the client using the `setGasPayer` method.
59
+
60
+ ```javascript Gas Payer Setup and Usage icon=logos:javascript
61
+ import Client from '@ocap/client';
62
+ import Wallet, { fromRandom } from '@ocap/wallet';
63
+
64
+ // 1. Initialize the client to connect to the Beta chain
65
+ const client = new Client('https://beta.abtnetwork.io/api');
66
+
67
+ // 2. Create a wallet for the gas payer (your application's wallet)
68
+ // This wallet must have enough native tokens (TBA) to cover transaction fees.
69
+ // You can get test tokens from the faucet: https://faucet.abtnetwork.io/
70
+ const gasPayerWallet = Wallet.fromJSON({
71
+ sk: '...your_sponsor_secret_key...',
72
+ pk: '...your_sponsor_public_key...',
73
+ address: '...your_sponsor_address...',
74
+ });
75
+
76
+ // 3. Set the gas payer on the client instance
77
+ client.setGasPayer(gasPayerWallet);
78
+
79
+ // 4. Create a wallet for the end-user.
80
+ const userWallet = fromRandom();
81
+
82
+ // 5. Send a transaction using the user's wallet.
83
+ // The transaction is signed by the user, but the gas fee is paid by gasPayerWallet.
84
+ async function performGaslessTransaction() {
85
+ try {
86
+ // Note: While a new account is created on-chain upon its first incoming transaction,
87
+ // it must exist on-chain before it can *send* transactions.
88
+ // You can initialize it by sending it a small amount of tokens from a faucet.
89
+
90
+ const receiverAddress = 'z1...'; // A valid recipient address
91
+ const hash = await client.transfer({
92
+ to: receiverAddress,
93
+ tokens: [{ value: '0.1' }], // Sending 0.1 TBA
94
+ wallet: userWallet,
95
+ });
96
+
97
+ console.log('Gasless transaction successful. Hash:', hash);
98
+ console.log(`Review on explorer: https://beta.abtnetwork.io/explorer/txs/${hash}`);
99
+ } catch (error) {
100
+ console.error('Transaction failed:', error);
101
+ }
102
+ }
103
+
104
+ performGaslessTransaction();
105
+ ```
106
+
107
+ In this example, `userWallet` can successfully send a transaction even with a zero balance of the native token, because `gasPayerWallet` covers the cost. This creates a frictionless experience, especially for new users joining your application.
108
+
109
+ ---
110
+
111
+ To understand the full journey of a transaction, from creation to finalization, see the [Transaction Lifecycle](./core-concepts-transaction-lifecycle.md) documentation.