使用 Dynamic Script Composer 调用 Move 链式交易
在基础 API 中,您只能为单个交易指定一个入口函数调用.而高级构建者可能希望在一个交易中调用多个 public Move 函数.现在通过交易构建器中提供的全新 scriptComposer
API 即可实现这一功能.
以下是调用该 API 的示例:
请注意当前实例仅为参考如何使用 Script Composer 组合交易的过程中接收 public 函数的返回值,并传递给下一个函数
const tx = await BuildScriptComposerTransaction({ // 这里需要填写 sender 的地址 sender: singleSignerED25519SenderAccount.accountAddress, builder: async (composer) => { // 开始取出一些 Coin const coin = await composer.addBatchedCalls({ function: "0x1::coin::withdraw", functionArguments: [CallArgument.newSigner(0), 1], typeArguments: ["0x1::aptos_coin::AptosCoin"], });
// 将 coin 值传递给 0x1::coin::coin_to_fungible_asset 将代币 // 转换为可替代资产 const fungibleAsset = await composer.addBatchedCalls({ function: "0x1::coin::coin_to_fungible_asset", // coin[0] 表示您添加的第一个调用的第一个返回值 functionArguments: [coin[0]], typeArguments: ["0x1::aptos_coin::AptosCoin"], });
// 存入从第二个调用转换得到的 fungibleAsset await composer.addBatchedCalls({ function: "0x1::primary_fungible_store::deposit", // 这里需要填写 sender 的地址 functionArguments: [singleSignerED25519SenderAccount.accountAddress, fungibleAsset[0]], typeArguments: [], }); return composer }, // 这里需要传递 Aptos Config ,因为组合交易需要读取链上状态 aptosConfig: new AptosConfig({ network: Network.TESTNET, }),});
组合交易后,我们可以使用 @aptos-labs/ts-sdk
中的 签名交易 / 模拟交易 / 提交交易等接口:
我们用 模拟交易接口展示如何使用
...
const aptos = new Aptos(new AptosConfig({ network: Network.TESTNET, }));
const simulate_result = await aptos.transaction.simulate.simple({ transaction: tx, })
console.log('simulate_result: ', simulate_result)...
如果你需要一些实际的案例,我们也为您准备了三种常见环境的使用案例:
在案例中,你将看到一个组合交易并模拟交易的返回值(模拟交易使用 0x1 地址作为 sender ,虽然默认状态下可以模拟成功, 但如果你想要真正使用这个功能发起模拟交易请替换成你帐户地址,并设置好对应的网络)
- nodejs: https://github.com/aptos-labs/script-composer-sdk/tree/main/examples/nodejs
- nextjs: https://github.com/aptos-labs/script-composer-sdk/tree/main/examples/nextjs-project
- react: https://github.com/aptos-labs/script-composer-sdk/tree/main/examples/react-project
在底层,SDK 会调用 WASM 二进制文件将一系列 Move 调用编译为 CompiledScript
.这将确保在构建过程中仍然遵循 Move 的类型和能力安全性.对于 SDK 用户而言,这意味着:
- 能力安全性: a. 如果返回值不具备 Drop 能力,则该返回值需要被后续调用消费 b. 如果返回值不具备 Copy 能力,则该返回值只能传递给后续调用一次
- 调用者需要确保将正确的值作为参数传递给后续调用.在前述示例中,
0x1::coin::coin_to_fungible_asset
函数需要接收一个Coin<AptosCoin>
类型的参数.
这实现了 AIP-102 规范