ts-sdk-transactions

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TypeScript SDK: Transactions

TypeScript SDK:交易

Purpose

用途

Guide building, signing, submitting, and simulating transactions with
@aptos-labs/ts-sdk
. Use the build → sign → submit → wait pattern; optionally simulate before submit.
本指南介绍如何使用
@aptos-labs/ts-sdk
构建、签名、提交和模拟交易。遵循「构建→签名→提交→等待上链」的流程,也可在提交前选择先模拟交易。

ALWAYS

必遵守则

  1. Call
    aptos.waitForTransaction({ transactionHash })
    after submit
    – do not assume transaction is committed after
    signAndSubmitTransaction
    .
  2. Use
    aptos.transaction.build.simple()
    for entry function payloads
    – pass
    sender
    and
    data: { function, functionArguments, typeArguments? }
    .
  3. Simulate before submit for critical/high-value flows – use
    aptos.transaction.simulate.simple()
    and check
    success
    and
    vm_status
    .
  4. Use the same Account instance for signer that you use for
    sender
    address when building (e.g.
    account.accountAddress
    as sender,
    account
    as signer).
  1. 提交后务必调用
    aptos.waitForTransaction({ transactionHash })
    :不要认为
    signAndSubmitTransaction
    返回后交易就已经上链确认。
  2. 入口函数 payload 请使用
    aptos.transaction.build.simple()
    构建
    :传入
    sender
    data: { function, functionArguments, typeArguments? }
    参数。
  3. 关键/高价值流程提交前务必模拟交易:使用
    aptos.transaction.simulate.simple()
    并校验
    success
    vm_status
    字段。
  4. 构建交易时
    sender
    地址对应的Account实例要和签名用的实例一致
    :例如
    sender
    account.accountAddress
    时,签名者也要用同一个
    account
    实例。

NEVER

禁止操作

  1. Do not skip
    waitForTransaction
    – submission returns when the tx is accepted, not when it is committed.
  2. Do not use deprecated
    scriptComposer
    (removed in v6) – use separate transactions or batch patterns.
  3. Do not use
    number
    for u64/u128/u256 in
    functionArguments
    – use
    bigint
    where required to avoid precision loss.

  1. 不要跳过
    waitForTransaction
    调用
    :提交接口返回仅代表交易被节点接收,不代表已经上链确认。
  2. 不要使用已废弃的
    scriptComposer
    (v6版本已移除):请改用多笔独立交易或批量交易模式。
  3. 不要在
    functionArguments
    中用
    number
    类型传递u64/u128/u256数值
    :需要时请使用
    bigint
    避免精度丢失。

Standard flow (simple transaction)

标准流程(简单交易)

typescript
import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";

const aptos = new Aptos(new AptosConfig({ network: Network.TESTNET }));
const MODULE_ADDRESS = "0x...";

// 1. Build
const transaction = await aptos.transaction.build.simple({
  sender: account.accountAddress,
  data: {
    function: `${MODULE_ADDRESS}::counter::increment`,
    functionArguments: [],
  },
});

// 2. Sign and submit
const pendingTx = await aptos.signAndSubmitTransaction({
  signer: account,
  transaction,
});

// 3. Wait for commitment
const committedTx = await aptos.waitForTransaction({
  transactionHash: pendingTx.hash,
});

if (!committedTx.success) {
  throw new Error(`Tx failed: ${committedTx.vm_status}`);
}

typescript
import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";

const aptos = new Aptos(new AptosConfig({ network: Network.TESTNET }));
const MODULE_ADDRESS = "0x...";

// 1. Build
const transaction = await aptos.transaction.build.simple({
  sender: account.accountAddress,
  data: {
    function: `${MODULE_ADDRESS}::counter::increment`,
    functionArguments: [],
  },
});

// 2. Sign and submit
const pendingTx = await aptos.signAndSubmitTransaction({
  signer: account,
  transaction,
});

// 3. Wait for commitment
const committedTx = await aptos.waitForTransaction({
  transactionHash: pendingTx.hash,
});

if (!committedTx.success) {
  throw new Error(`Tx failed: ${committedTx.vm_status}`);
}

Build options

构建可选参数

typescript
// With type arguments (e.g. coin type)
const transaction = await aptos.transaction.build.simple({
  sender: account.accountAddress,
  data: {
    function: "0x1::coin::transfer",
    typeArguments: ["0x1::aptos_coin::AptosCoin"],
    functionArguments: [recipientAddress, amount],
  },
});

// Optional: max gas, expiry, etc. (see SDK types for full options)
const transactionWithOptions = await aptos.transaction.build.simple({
  sender: account.accountAddress,
  data: { function: "...", functionArguments: [] },
  options: {
    maxGasAmount: 2000n,
    gasUnitPrice: 100n,
    expireTimestamp: BigInt(Math.floor(Date.now() / 1000) + 600),
  },
});

typescript
// With type arguments (e.g. coin type)
const transaction = await aptos.transaction.build.simple({
  sender: account.accountAddress,
  data: {
    function: "0x1::coin::transfer",
    typeArguments: ["0x1::aptos_coin::AptosCoin"],
    functionArguments: [recipientAddress, amount],
  },
});

// Optional: max gas, expiry, etc. (see SDK types for full options)
const transactionWithOptions = await aptos.transaction.build.simple({
  sender: account.accountAddress,
  data: { function: "...", functionArguments: [] },
  options: {
    maxGasAmount: 2000n,
    gasUnitPrice: 100n,
    expireTimestamp: BigInt(Math.floor(Date.now() / 1000) + 600),
  },
});

Simulation (before submit)

交易模拟(提交前执行)

typescript
const transaction = await aptos.transaction.build.simple({
  sender: account.accountAddress,
  data: {
    function: `${MODULE_ADDRESS}::counter::increment`,
    functionArguments: [],
  },
});

const [simResult] = await aptos.transaction.simulate.simple({
  signerPublicKey: account.publicKey,
  transaction,
});

if (!simResult.success) {
  throw new Error(`Simulation failed: ${simResult.vm_status}`);
}
console.log("Gas used:", simResult.gas_used);

typescript
const transaction = await aptos.transaction.build.simple({
  sender: account.accountAddress,
  data: {
    function: `${MODULE_ADDRESS}::counter::increment`,
    functionArguments: [],
  },
});

const [simResult] = await aptos.transaction.simulate.simple({
  signerPublicKey: account.publicKey,
  transaction,
});

if (!simResult.success) {
  throw new Error(`Simulation failed: ${simResult.vm_status}`);
}
console.log("Gas used:", simResult.gas_used);

Sponsored transactions (fee payer)

赞助交易(第三方付费)

typescript
// 1. Build with fee payer
const transaction = await aptos.transaction.build.simple({
  sender: sender.accountAddress,
  withFeePayer: true,
  data: {
    function: `${MODULE_ADDRESS}::counter::increment`,
    functionArguments: [],
  },
});

// 2. Sender signs
const senderAuth = aptos.transaction.sign({
  signer: sender,
  transaction,
});

// 3. Fee payer signs (different method)
const feePayerAuth = aptos.transaction.signAsFeePayer({
  signer: feePayer,
  transaction,
});

// 4. Submit with both authenticators
const pendingTx = await aptos.transaction.submit.simple({
  transaction,
  senderAuthenticator: senderAuth,
  feePayerAuthenticator: feePayerAuth,
});

await aptos.waitForTransaction({ transactionHash: pendingTx.hash });

typescript
// 1. Build with fee payer
const transaction = await aptos.transaction.build.simple({
  sender: sender.accountAddress,
  withFeePayer: true,
  data: {
    function: `${MODULE_ADDRESS}::counter::increment`,
    functionArguments: [],
  },
});

// 2. Sender signs
const senderAuth = aptos.transaction.sign({
  signer: sender,
  transaction,
});

// 3. Fee payer signs (different method)
const feePayerAuth = aptos.transaction.signAsFeePayer({
  signer: feePayer,
  transaction,
});

// 4. Submit with both authenticators
const pendingTx = await aptos.transaction.submit.simple({
  transaction,
  senderAuthenticator: senderAuth,
  feePayerAuthenticator: feePayerAuth,
});

await aptos.waitForTransaction({ transactionHash: pendingTx.hash });

Multi-agent transactions

多Agent交易

typescript
const transaction = await aptos.transaction.build.multiAgent({
  sender: alice.accountAddress,
  secondarySignerAddresses: [bob.accountAddress],
  data: {
    function: `${MODULE_ADDRESS}::escrow::exchange`,
    functionArguments: [itemAddress, amount],
  },
});

const aliceAuth = aptos.transaction.sign({ signer: alice, transaction });
const bobAuth = aptos.transaction.sign({ signer: bob, transaction });

const pendingTx = await aptos.transaction.submit.multiAgent({
  transaction,
  senderAuthenticator: aliceAuth,
  additionalSignersAuthenticators: [bobAuth],
});

await aptos.waitForTransaction({ transactionHash: pendingTx.hash });

typescript
const transaction = await aptos.transaction.build.multiAgent({
  sender: alice.accountAddress,
  secondarySignerAddresses: [bob.accountAddress],
  data: {
    function: `${MODULE_ADDRESS}::escrow::exchange`,
    functionArguments: [itemAddress, amount],
  },
});

const aliceAuth = aptos.transaction.sign({ signer: alice, transaction });
const bobAuth = aptos.transaction.sign({ signer: bob, transaction });

const pendingTx = await aptos.transaction.submit.multiAgent({
  transaction,
  senderAuthenticator: aliceAuth,
  additionalSignersAuthenticators: [bobAuth],
});

await aptos.waitForTransaction({ transactionHash: pendingTx.hash });

waitForTransaction options

waitForTransaction可选参数

typescript
const committed = await aptos.waitForTransaction({
  transactionHash: pendingTx.hash,
  options: {
    timeoutSecs: 60,
    checkSuccess: true,  // throw if tx failed
  },
});

typescript
const committed = await aptos.waitForTransaction({
  transactionHash: pendingTx.hash,
  options: {
    timeoutSecs: 60,
    checkSuccess: true,  // throw if tx failed
  },
});

Gas profiling

Gas分析

typescript
const gasProfile = await aptos.gasProfile({
  sender: account.accountAddress,
  data: {
    function: `${MODULE_ADDRESS}::module::function_name`,
    functionArguments: [],
  },
});
console.log("Gas profile:", gasProfile);

typescript
const gasProfile = await aptos.gasProfile({
  sender: account.accountAddress,
  data: {
    function: `${MODULE_ADDRESS}::module::function_name`,
    functionArguments: [],
  },
});
console.log("Gas profile:", gasProfile);

Common mistakes

常见错误

MistakeCorrect approach
Not calling waitForTransactionAlways wait and check
committedTx.success
Using number for large amountsUse
bigint
for u64/u128/u256 in functionArguments
Wrong signer for submitUse the Account whose address is the sender (or fee payer / additional signer as appropriate)
Assuming scriptComposer existsUse separate transactions or batch; scriptComposer removed in v6

错误做法正确方案
未调用waitForTransaction始终等待交易上链并校验
committedTx.success
字段
大数值使用number类型传递在functionArguments中用
bigint
传递u64/u128/u256类型数值
提交时签名者不匹配使用sender地址对应的Account实例作为签名者(付费方/额外签名方同理)
假设scriptComposer可用使用独立交易或批量模式,scriptComposer在v6版本已移除

References

参考资料

  • SDK:
    src/api/transaction.ts
    ,
    src/internal/transactionSubmission.ts
    ,
    src/internal/transaction.ts
  • Pattern: TYPESCRIPT_SDK.md
  • Related: ts-sdk-account, ts-sdk-client, ts-sdk-wallet-adapter, use-ts-sdk
  • SDK源码:
    src/api/transaction.ts
    src/internal/transactionSubmission.ts
    src/internal/transaction.ts
  • 开发模式:TYPESCRIPT_SDK.md
  • 相关内容:ts-sdk-accountts-sdk-clientts-sdk-wallet-adapteruse-ts-sdk