跳转到内容

运行 Move 脚本

Aptos TypeScript SDK、Aptos Wallet Adapter 和 Aptos CLI 均支持 Move 脚本。

要通过 TypeScript SDK 使用脚本,请直接将 bytecode 加入交易数据,以取代入口函数名称。

import { readFileSync } from "fs";
import { Aptos, Account, AccountAddress } from "@aptos-labs/ts-sdk";
// Setup client, and account to sign
const aptos = new Aptos();
const account = Account.generate();
// Load script bytecode
const buffer = readFileSync("./transfer_half.mv", "buffer");
const bytecode = new Uint8Array.from(buffer);
// Build a transaction with the bytecode of the script
const 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 complete
const pendingTxn = await aptos.signAndSubmitTransaction({
signer: account,
transaction,
});
await aptos.waitForTransaction({ transactionHash: pendingTxn.hash });

与 TypeScript SDK 类似,钱包适配器将相同输入作为交易类型接受。只需将字节码加载为十六进制 stringuint8array

import { useWallet } from "@aptos-labs/wallet-adapter-react";
//...
// Load the bytecode either as a uint8array or a hex encoded string
const 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 运行脚本:

Terminal window
aptos move run-script

运行方式有两种:运行预编译脚本,或像编译步骤一样就地编译脚本。

如果已有编译后的脚本,可按以下示例使用 --compiled-script-path 运行:

Terminal window
aptos move run-script --compiled-script-path /opt/git/developer-docs/apps/docusaurus/static/move-examples/scripts/transfer_half/script.mv

同样地,如果尚未编译,只需使用 --script-path

Terminal window
aptos move run-script --script-path ./sources/transfer_half.move