运行 Move 脚本
Aptos TypeScript SDK、Aptos Wallet Adapter 和 Aptos CLI 均支持 Move 脚本。
使用 TypeScript SDK 运行脚本
Section titled “使用 TypeScript SDK 运行脚本”要通过 TypeScript SDK 使用脚本,请直接将 bytecode 加入交易数据,以取代入口函数名称。
import { readFileSync } from "fs";import { Aptos, Account, AccountAddress } from "@aptos-labs/ts-sdk";
// Setup client, and account to signconst aptos = new Aptos();const account = Account.generate();
// Load script bytecodeconst buffer = readFileSync("./transfer_half.mv", "buffer");const bytecode = new Uint8Array.from(buffer);
// Build a transaction with the bytecode of the scriptconst transaction = await aptos.transaction.build.simple({ sender: account.accountAddress, data: { bytecode, typeArguments: [parseTypeTag("0x1::aptos_coin::AptosCoin")], functionArguments: [AccountAddress.from("0x1")], },});
// Submit and wait for the transaction to completeconst pendingTxn = await aptos.signAndSubmitTransaction({ signer: account, transaction,});await aptos.waitForTransaction({ transactionHash: pendingTxn.hash });使用 Aptos Wallet Adapter 运行脚本
Section titled “使用 Aptos Wallet Adapter 运行脚本”与 TypeScript SDK 类似,钱包适配器将相同输入作为交易类型接受。只需将字节码加载为十六进制 string 或 uint8array。
import { useWallet } from "@aptos-labs/wallet-adapter-react";
//...
// Load the bytecode either as a uint8array or a hex encoded stringconst BYTECODE_IN_HEX = "0xa11ceb0b...78979";
export default function App() { const { signAndSubmitTransaction } = useWallet();
function submitScript() { signAndSubmitTransaction({ data: { bytecode: BYTECODE_IN_HEX, typeArguments: [parseTypeTag("0x1::aptos_coin::AptosCoin")], functionArguments: [AccountAddress.from("0x1")], }, }); }
// ...}使用 CLI 运行脚本
Section titled “使用 CLI 运行脚本”可使用以下命令通过 CLI 运行脚本:
aptos move run-script运行方式有两种:运行预编译脚本,或像编译步骤一样就地编译脚本。
如果已有编译后的脚本,可按以下示例使用 --compiled-script-path 运行:
aptos move run-script --compiled-script-path /opt/git/developer-docs/apps/docusaurus/static/move-examples/scripts/transfer_half/script.mv同样地,如果尚未编译,只需使用 --script-path:
aptos move run-script --script-path ./sources/transfer_half.move