Aptos?SDK交互實(shí)現(xiàn)過程詳解
背景
之前我們已經(jīng)了解TS的一些語法,接下來可以實(shí)戰(zhàn)訓(xùn)練下,這系列的文章就會(huì)介紹如何通過Aptos官網(wǎng)提供的TypeScript SDK與Aptos進(jìn)行交互,這篇文章主要講的就是如何使用提供API在aptos區(qū)塊鏈上轉(zhuǎn)帳。
官網(wǎng)示例
官網(wǎng)提供了交互的例子,我們需要先clone下倉庫
git clone https://github.com/aptos-labs/aptos-core.git
然后進(jìn)入例子的文件中
cd ~/aptos-core/ecosystem/typescript/sdk/examples/typescript
然后安裝必要的依賴,這里使用的是pnpm,如果沒有安裝pnpm則需要先安裝一下,然后用一下命令來安裝依賴
pnpm install
然后通過以下命令來運(yùn)行例子
pnpm run transfer_coin
接著就會(huì)看到以下輸出:
=== Addresses ===
Alice: 0x98b90c8febd6a248374f11d409045e9e06a68e3ae8688b00c99cf6c2218cbc18
Bob: 0x5a22c7704392910541ee53960477722c3aec0667b2bcb3da954f8e06490b39d3=== Initial Balances ===
Alice: 100000000
Bob: 0=== Intermediate Balances ===
Alice: 99944800
Bob: 1000=== Final Balances ===
Alice: 99889600
Bob: 2000
這期間經(jīng)過具體的步驟如下
- 初始化REST和facuet客戶端
- 創(chuàng)建兩個(gè)賬戶Alice和Bob
- Alice賬戶從facuet領(lǐng)取代幣
- Alice轉(zhuǎn)賬1000代幣個(gè)Bob并支付gas費(fèi)
- Alice再次轉(zhuǎn)帳1000代幣給Bob并支付gas費(fèi)
實(shí)現(xiàn)過程
之前我們已經(jīng)大概了解了這個(gè)例子做的事情,那么這又是怎么實(shí)現(xiàn)的呢,接下來我們可以一步一步看代碼:
初始化客戶端
第一步我們就要初始化REST和facuet客戶端。
- REST客戶端是用來和REST API交互的
- facuet客戶端是用來與開發(fā)網(wǎng)Faucet服務(wù)交互的,可以創(chuàng)建賬戶和獲取測(cè)試代幣
const client = new AptosClient(NODE_URL); const faucetClient = new FaucetClient(NODE_URL, FAUCET_URL);
使用API client我們可以創(chuàng)建一個(gè)CoinClient,使用CoinClient可以進(jìn)行常規(guī)的賬戶操作如轉(zhuǎn)帳和檢查余額。
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";
?在默認(rèn)情況下URL都是指向開發(fā)網(wǎng)的服務(wù),但是我們也可以通過以下兩個(gè)環(huán)境變量配置:?
- APTOS_NODE_URL - APTOS_FAUCET_URL
創(chuàng)建本地賬戶
接下來需要?jiǎng)?chuàng)建兩個(gè)本地賬戶,賬戶有鏈上狀態(tài)和鏈下狀態(tài),鏈下狀態(tài)由一個(gè)地址和一個(gè)公鑰/私鑰對(duì)組成,私鑰是用來驗(yàn)證所有權(quán)的,下面代碼創(chuàng)建了鏈下狀態(tài):
const alice = new AptosAccount(); const bob = new AptosAccount();
創(chuàng)建區(qū)塊鏈賬戶
在Aptos中,每一個(gè)賬戶都必須要有一個(gè)鏈上代表用于接收代幣以及與其他dAPP交互,一個(gè)賬戶代表了存儲(chǔ)資產(chǎn)的媒介,以下代碼說明了如何使用Faucet創(chuàng)建賬戶,然后獲取代幣。
await faucetClient.fundAccount(alice.address(), 100_000_000); await faucetClient.fundAccount(bob.address(), 0);
讀取余額
以下代碼說明如何去獲取賬戶余額,在這個(gè)背景下,SDK中的CoinClient函數(shù)checkBalance可以查詢現(xiàn)在存儲(chǔ)的值
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); }
轉(zhuǎn)帳
與上一步一樣,這是另一個(gè)幫助步驟,它構(gòu)建了一個(gè)將硬幣從 Alice 轉(zhuǎn)移到 Bob 的交易。對(duì)于正確生成的交易,API 將返回交易哈希,可在后續(xù)步驟中使用該哈希來檢查交易狀態(tài)。 Aptos 區(qū)塊鏈確實(shí)對(duì)提交進(jìn)行了一些驗(yàn)證檢查;如果其中任何一個(gè)失敗,用戶將收到錯(cuò)誤消息。這些驗(yàn)證使用交易簽名和未使用的序列號(hào),并將交易提交到適當(dāng)?shù)逆湣?/p>
let txnHash = await coinClient.transfer(alice, bob, 1_000, { gasUnitPrice: BigInt(100) });
在幕后,傳輸函數(shù)生成交易負(fù)載并讓客戶端簽名、發(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的內(nèi)容如下
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 中,只需調(diào)用 coinClient.transfer 就足以等待交易完成。一旦處理(成功或不成功),該函數(shù)將返回 API 返回的事務(wù),或者如果處理時(shí)間超過超時(shí)則拋出錯(cuò)誤。如果您希望在事務(wù)未成功提交時(shí)拋出錯(cuò)誤,則可以在調(diào)用 transfer 時(shí)將 checkSuccess 設(shè)置為 true:
await client.waitForTransaction(txnHash);
以上就是Aptos SDK交互實(shí)現(xiàn)過程詳解的詳細(xì)內(nèi)容,更多關(guān)于Aptos SDK交互的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
quickjs調(diào)用lvgl函數(shù)的示例代碼
這篇文章主要介紹了quickjs調(diào)用lvgl函數(shù),實(shí)現(xiàn)本次使用quickjs的最主要目的,就是通過程序動(dòng)態(tài)加載js,然后調(diào)用lvgl函數(shù)庫,實(shí)現(xiàn)渲染,需要的朋友可以參考下2023-11-11前端URL拼接路徑參數(shù)具體實(shí)現(xiàn)代碼
這篇文章主要給大家介紹了關(guān)于前端URL拼接路徑參數(shù)具體實(shí)現(xiàn)的相關(guān)資料,url地址拼接是經(jīng)常會(huì)遇到的問題,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12如何利用js根據(jù)坐標(biāo)判斷構(gòu)成單個(gè)多邊形是否合法
這篇文章主要給大家介紹了關(guān)于如何利用js根據(jù)坐標(biāo)判斷構(gòu)成單個(gè)多邊形是否合法的相關(guān)資料,文章通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2022-01-01JavaScript基于ChatGPT?API實(shí)現(xiàn)劃詞翻譯瀏覽器腳本
最近?GitHub?上有個(gè)基于?ChatGPT?API?的瀏覽器腳本,openai-translator,?短時(shí)間內(nèi)?star?沖到了?9.7k,拋開?tauri?是使用?rust?部分,那瀏覽器部分實(shí)現(xiàn)還是比較簡(jiǎn)單的,今天我們就來手動(dòng)實(shí)現(xiàn)一下2023-03-03解析javascript系統(tǒng)錯(cuò)誤:-1072896658的解決辦法
問題出現(xiàn)在用到ajax的場(chǎng)合。昨天還正常的程序,今天運(yùn)行就有javascript系統(tǒng)錯(cuò)誤:-1072896658的2013-07-07