Aptos?SDK交互實現過程詳解
背景
之前我們已經了解TS的一些語法,接下來可以實戰(zhàn)訓練下,這系列的文章就會介紹如何通過Aptos官網提供的TypeScript SDK與Aptos進行交互,這篇文章主要講的就是如何使用提供API在aptos區(qū)塊鏈上轉帳。
官網示例
官網提供了交互的例子,我們需要先clone下倉庫
git clone https://github.com/aptos-labs/aptos-core.git
然后進入例子的文件中
cd ~/aptos-core/ecosystem/typescript/sdk/examples/typescript
然后安裝必要的依賴,這里使用的是pnpm,如果沒有安裝pnpm則需要先安裝一下,然后用一下命令來安裝依賴
pnpm install
然后通過以下命令來運行例子
pnpm run transfer_coin
接著就會看到以下輸出:
=== Addresses ===
Alice: 0x98b90c8febd6a248374f11d409045e9e06a68e3ae8688b00c99cf6c2218cbc18
Bob: 0x5a22c7704392910541ee53960477722c3aec0667b2bcb3da954f8e06490b39d3=== Initial Balances ===
Alice: 100000000
Bob: 0=== Intermediate Balances ===
Alice: 99944800
Bob: 1000=== Final Balances ===
Alice: 99889600
Bob: 2000
這期間經過具體的步驟如下
- 初始化REST和facuet客戶端
- 創(chuàng)建兩個賬戶Alice和Bob
- Alice賬戶從facuet領取代幣
- Alice轉賬1000代幣個Bob并支付gas費
- Alice再次轉帳1000代幣給Bob并支付gas費
實現過程
之前我們已經大概了解了這個例子做的事情,那么這又是怎么實現的呢,接下來我們可以一步一步看代碼:
初始化客戶端
第一步我們就要初始化REST和facuet客戶端。
- REST客戶端是用來和REST API交互的
- facuet客戶端是用來與開發(fā)網Faucet服務交互的,可以創(chuàng)建賬戶和獲取測試代幣
const client = new AptosClient(NODE_URL); const faucetClient = new FaucetClient(NODE_URL, FAUCET_URL);
使用API client我們可以創(chuàng)建一個CoinClient,使用CoinClient可以進行常規(guī)的賬戶操作如轉帳和檢查余額。
const coinClient = new CoinClient(client);
在common.ts中初始化來URL如下
export const NODE_URL = process.env.APTOS_NODE_URL || "https://fullnode.devnet.aptoslabs.com"; export const FAUCET_URL = process.env.APTOS_FAUCET_URL || "https://faucet.devnet.aptoslabs.com";
?在默認情況下URL都是指向開發(fā)網的服務,但是我們也可以通過以下兩個環(huán)境變量配置:?
- APTOS_NODE_URL - APTOS_FAUCET_URL
創(chuàng)建本地賬戶
接下來需要創(chuàng)建兩個本地賬戶,賬戶有鏈上狀態(tài)和鏈下狀態(tài),鏈下狀態(tài)由一個地址和一個公鑰/私鑰對組成,私鑰是用來驗證所有權的,下面代碼創(chuàng)建了鏈下狀態(tài):
const alice = new AptosAccount(); const bob = new AptosAccount();
創(chuàng)建區(qū)塊鏈賬戶
在Aptos中,每一個賬戶都必須要有一個鏈上代表用于接收代幣以及與其他dAPP交互,一個賬戶代表了存儲資產的媒介,以下代碼說明了如何使用Faucet創(chuàng)建賬戶,然后獲取代幣。
await faucetClient.fundAccount(alice.address(), 100_000_000); await faucetClient.fundAccount(bob.address(), 0);
讀取余額
以下代碼說明如何去獲取賬戶余額,在這個背景下,SDK中的CoinClient函數checkBalance可以查詢現在存儲的值
console.log(`Alice: ${await coinClient.checkBalance(alice)}`); console.log(`Bob: ${await coinClient.checkBalance(bob)}`);
async checkBalance( account: AptosAccount | MaybeHexString, extraArgs?: { // The coin type to use, defaults to 0x1::aptos_coin::AptosCoin coinType?: string; }, ): Promise<bigint> { const coinType = extraArgs?.coinType ?? APTOS_COIN; const typeTag = `0x1::coin::CoinStore<${coinType}>`; const address = getAddressFromAccountOrAddress(account); const accountResource = await this.aptosClient.getAccountResource(address, typeTag); return BigInt((accountResource.data as any).coin.value); }
轉帳
與上一步一樣,這是另一個幫助步驟,它構建了一個將硬幣從 Alice 轉移到 Bob 的交易。對于正確生成的交易,API 將返回交易哈希,可在后續(xù)步驟中使用該哈希來檢查交易狀態(tài)。 Aptos 區(qū)塊鏈確實對提交進行了一些驗證檢查;如果其中任何一個失敗,用戶將收到錯誤消息。這些驗證使用交易簽名和未使用的序列號,并將交易提交到適當的鏈。
let txnHash = await coinClient.transfer(alice, bob, 1_000, { gasUnitPrice: BigInt(100) });
在幕后,傳輸函數生成交易負載并讓客戶端簽名、發(fā)送并等待它:
async transfer( from: AptosAccount, to: AptosAccount | MaybeHexString, amount: number | bigint, extraArgs?: OptionalTransactionArgs & { // The coin type to use, defaults to 0x1::aptos_coin::AptosCoin coinType?: string; // If set, create the `receiver` account if it doesn't exist on-chain. // This is done by calling `0x1::aptos_account::transfer` instead, which // will create the account on-chain first if it doesn't exist before // transferring the coins to it. createReceiverIfMissing?: boolean; }, ): Promise<string> { // If none is explicitly given, use 0x1::aptos_coin::AptosCoin as the coin type. const coinTypeToTransfer = extraArgs?.coinType ?? APTOS_COIN; // If we should create the receiver account if it doesn't exist on-chain, // use the `0x1::aptos_account::transfer` function. const func = extraArgs?.createReceiverIfMissing ? "0x1::aptos_account::transfer" : "0x1::coin::transfer"; // If we're using the `0x1::aptos_account::transfer` function, we don't // need type args. const typeArgs = extraArgs?.createReceiverIfMissing ? [] : [coinTypeToTransfer]; // Get the receiver address from the AptosAccount or MaybeHexString. const toAddress = getAddressFromAccountOrAddress(to); const payload = this.transactionBuilder.buildTransactionPayload(func, typeArgs, [toAddress, amount]); return this.aptosClient.generateSignSubmitTransaction(from, payload, extraArgs); }
generateSignSubmitTransaction的內容如下
const rawTransaction = await this.generateRawTransaction(sender.address(), payload, extraArgs); const bcsTxn = AptosClient.generateBCSTransaction(sender, rawTransaction); const pendingTransaction = await this.submitSignedBCSTransaction(bcsTxn); return pendingTransaction.hash;
等待交易處理
在 TypeScript 中,只需調用 coinClient.transfer 就足以等待交易完成。一旦處理(成功或不成功),該函數將返回 API 返回的事務,或者如果處理時間超過超時則拋出錯誤。如果您希望在事務未成功提交時拋出錯誤,則可以在調用 transfer 時將 checkSuccess 設置為 true:
await client.waitForTransaction(txnHash);
以上就是Aptos SDK交互實現過程詳解的詳細內容,更多關于Aptos SDK交互的資料請關注腳本之家其它相關文章!
相關文章
JavaScript基于ChatGPT?API實現劃詞翻譯瀏覽器腳本
最近?GitHub?上有個基于?ChatGPT?API?的瀏覽器腳本,openai-translator,?短時間內?star?沖到了?9.7k,拋開?tauri?是使用?rust?部分,那瀏覽器部分實現還是比較簡單的,今天我們就來手動實現一下2023-03-03解析javascript系統(tǒng)錯誤:-1072896658的解決辦法
問題出現在用到ajax的場合。昨天還正常的程序,今天運行就有javascript系統(tǒng)錯誤:-1072896658的2013-07-07