今天小编给大家分享一下Aptos SDK交互如何实现的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下...
今天小编给大家分享一下Aptos SDK交互如何实现的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。
官网示例
官网提供了交互的例子,我们需要先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客户端。
const client = new AptosClient(NODE_URL);
const faucetClient = new FaucetClient(NODE_URL, FAUCET_URL);
使用API client我们可以创建一个CoinClient,使用CoinClient可以进行常规的账户操作如转帐和检查余额。
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都是指向开发网的服务,但是我们也可以通过以下两个环境变量配置:
- APTOS_NODE_URL
- APTOS_FAUCET_URL
创建本地账户
接下来需要创建两个本地账户,账户有链上状态和链下状态,链下状态由一个地址和一个公钥/私钥对组成,私钥是用来验证所有权的,下面代码创建了链下状态:
const alice = new AptosAccount();
const bob = new AptosAccount();
创建区块链账户
在Aptos中,每一个账户都必须要有一个链上代表用于接收代币以及与其他dAPP交互,一个账户代表了存储资产的媒介,以下代码说明了如何使用Faucet创建账户,然后获取代币。
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 将返回交易哈希,可在后续步骤中使用该哈希来检查交易状态。 Aptos 区块链确实对提交进行了一些验证检查;如果其中任何一个失败,用户将收到错误消息。这些验证使用交易签名和未使用的序列号,并将交易提交到适当的链。
let txnHash = await coinClient.transfer(alice, bob, 1_000, { gasUnitPrice: BigInt(100) });
在幕后,传输函数生成交易负载并让客户端签名、发送并等待它:
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交互如何实现”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注捷杰建站行业资讯频道。