@aptos-labs/ts-sdk

中文文档
7.5.0发布于 2026/10/10SEE LICENSE IN LICENSETypeScriptES Module构建来源已验证近 30 天下载 67.6万

Aptos TypeScript SDK

原始使用文档
文档目录16 节
  1. Learn More
  2. Installation
  3. For use in Node.js or a web application
  4. For use with Bun
  5. For use in a browser
  6. Usage
  7. Option 1: Aptos class (all-in-one)
  8. Option 2: Namespace classes from sub-paths (tree-shakeable)
  9. Option 3: Standalone functions (maximum tree-shaking)
  10. Reading Data From Onchain ( Guide )
  11. Account management (default to Ed25519)
  12. Submit transaction ( Tutorial )
  13. Using Struct and Enum Arguments
  14. Troubleshooting
  15. Contributing
  16. Running unit tests

TypeScript SDK for Aptos

NPM Package Version Node Version NPM Package Downloads

The TypeScript SDK allows you to connect, explore, and interact with the Aptos blockchain. You can use it to request data, send transactions, set up test environments, and more!

Learn More

For comprehensive guides, tutorials, and API reference, visit aptos.dev:

Installation

For use in Node.js or a web application

Install with your favorite package manager such as npm, yarn, or pnpm:

pnpm install @aptos-labs/ts-sdk

For use with Bun

The SDK is compatible with the Bun runtime. Install the SDK using Bun's package manager:

bun add @aptos-labs/ts-sdk

For use in a browser

The SDK is ESM-only and works with any modern bundler (Vite, webpack, etc.):

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

Usage

Option 1: Aptos class (all-in-one)

The simplest way to get started. Not tree-shakeable — pulls in all sub-modules.

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

const config = new AptosConfig({ network: Network.TESTNET });
const aptos = new Aptos(config);

Option 2: Namespace classes from sub-paths (tree-shakeable)

Import only the namespaces you need for smaller bundles with full autocomplete:

import { Network } from "@aptos-labs/ts-sdk";
import { General, AptosConfig } from "@aptos-labs/ts-sdk/general";
import { Faucet } from "@aptos-labs/ts-sdk/faucet";

const config = new AptosConfig({ network: Network.TESTNET });
const general = new General(config);
const faucet = new Faucet(config);

Option 3: Standalone functions (maximum tree-shaking)

For the smallest possible bundles (e.g., wallet adapters), import the standalone functions from their sub-paths. AptosConfig / Network are also available from their sub-paths (@aptos-labs/ts-sdk/general), but importing them from the main barrel is fine — the package is marked sideEffects: false, so modern bundlers still tree-shake unused exports.

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

const config = new AptosConfig({ network: Network.TESTNET });
const ledger = await getLedgerInfo({ aptosConfig: config });

Reading Data From Onchain (Guide)


const accountInfo = await aptos.account.getAccountInfo({ accountAddress: "0x123" });
const modules = await aptos.account.getAccountModules({ accountAddress: "0x123" });
const tokens = await aptos.account.getAccountOwnedTokens({ accountAddress: "0x123" });

Reading pruned history

Public fullnodes only retain a rolling window of recent history. Reads outside that window fail with 410 Gone and an archival_endpoint naming a node that still holds the data. The SDK retries those reads against that endpoint and returns the result transparently, so historical queries keep working without any code change.

Credentials are only sent to the archival endpoint when it is on the same site as the node you configured, since that endpoint is chosen by the node rather than by you. To disable the retry:

const aptos = new Aptos(new AptosConfig({ network: Network.TESTNET, archivalFallback: false }));

Note: getTransactionByHash is not covered. A pruned node cannot tell a pruned transaction from one that never existed, so it answers 404 with no archival hint. Use getTransactionByVersion for historical lookups, or point fullnode at an archival endpoint directly.

Account management (default to Ed25519)

Note: We introduce a Single Sender authentication (as introduced in AIP-55). Generating an account defaults to Legacy Ed25519 authentication with the option to use the Single Sender unified authentication.


Generate new keys

const account = Account.generate(); // defaults to Legacy Ed25519
const account = Account.generate({ scheme: SigningSchemeInput.Secp256k1Ecdsa }); // Single Sender Secp256k1
const account = Account.generate({ scheme: SigningSchemeInput.Ed25519, legacy: false }); // Single Sender Ed25519

Derive from private key

// Create a private key instance for Ed25519 scheme
const privateKey = new Ed25519PrivateKey("myEd25519privatekeystring");
// Or for Secp256k1 scheme
const privateKey = new Secp256k1PrivateKey("mySecp256k1privatekeystring");

// Derive an account from private key

// This is used as a local calculation and therefore is used to instantiate an `Account`
// that has not had its authentication key rotated
const account = Account.fromPrivateKey({ privateKey });

// Also, can use this function that resolves the provided private key type and derives the public key from it
// to support key rotation and differentiation between Legacy Ed25519 and Unified authentications
const aptos = new Aptos();
const account = await aptos.deriveAccountFromPrivateKey({ privateKey });

Derive from private key and address

// Create a private key instance for Ed25519 scheme
const privateKey = new Ed25519PrivateKey("myEd25519privatekeystring");
// Or for Secp256k1 scheme
const privateKey = new Secp256k1PrivateKey("mySecp256k1privatekeystring");

// Derive an account from private key and address

// Create an AccountAddress instance from the account address string.
const address = AccountAddress.from("myaccountaddressstring");
// Derive an account from private key and address
const account = Account.fromPrivateKeyAndAddress({ privateKey, address });

Derive from path

const path = "m/44'/637'/0'/0'/1";
const mnemonic = "various float stumble...";
const account = Account.fromDerivationPath({ path, mnemonic });

Submit transaction (Tutorial)


/**
 * This example shows how to use the Aptos SDK to send a transaction.
 * Don't forget to install @aptos-labs/ts-sdk before running this example!
 */

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

async function example() {
    console.log("This example will create two accounts (Alice and Bob) and send a transaction transferring APT to Bob's account.");

    // 0. Setup the client and test accounts
    const config = new AptosConfig({ network: Network.TESTNET });
    const aptos = new Aptos(config);

    let alice = Account.generate();
    let bob = Account.generate();

    console.log("=== Addresses ===\n");
    console.log(`Alice's address is: ${alice.accountAddress}`);
    console.log(`Bob's address is: ${bob.accountAddress}`);

    console.log("\n=== Funding accounts ===\n");
    await aptos.faucet.fundAccount({
        accountAddress: alice.accountAddress,
        amount: 100_000_000,
    });
    await aptos.faucet.fundAccount({
        accountAddress: bob.accountAddress,
        amount: 100,
    });
    console.log("Funded Alice and Bob's accounts!")

    // 1. Build
    console.log("\n=== 1. Building the transaction ===\n");
    const transaction = await aptos.transaction.build.simple({
        sender: alice,
        data: {
        // All transactions on Aptos are implemented via smart contracts.
        function: "0x1::aptos_account::transfer",
        functionArguments: [bob.accountAddress, 100],
        },
    });
    console.log("Built the transaction!")

    // 2. Simulate (Optional)
    console.log("\n === 2. Simulating Response (Optional) === \n")
    const [userTransactionResponse] = await aptos.transaction.simulate.simple({
        transaction,
    });
    console.log(userTransactionResponse)

    // 3. Sign
    console.log("\n=== 3. Signing transaction ===\n");
    const senderAuthenticator = aptos.transaction.sign({
        signer: alice,
        transaction,
    });
    console.log("Signed the transaction!")

    // 4. Submit
    console.log("\n=== 4. Submitting transaction ===\n");
    const submittedTransaction = await aptos.transaction.submit.simple({
        transaction,
        senderAuthenticator,
    });

    console.log(`Submitted transaction hash: ${submittedTransaction.hash}`);

    // 5. Wait for results
    console.log("\n=== 5. Waiting for result of transaction ===\n");
    const executedTransaction = await aptos.transaction.waitForTransaction({ transactionHash: submittedTransaction.hash });
    console.log(executedTransaction)
};

example();

Using Struct and Enum Arguments


The SDK supports passing public copy structs and enums as transaction arguments. You must encode them using the StructEnumArgumentParser before passing to transaction building functions:

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

const config = new AptosConfig({ network: Network.TESTNET });
const aptos = new Aptos(config);
const parser = new StructEnumArgumentParser(config);

// Example 1: Simple struct argument
const pointType = parseTypeTag("0x1::shapes::Point") as TypeTagStruct;
const pointArg = await parser.encodeStructArgument(pointType, { x: "10", y: "20" });

const transaction = await aptos.transaction.build.simple({
  sender: alice.accountAddress,
  data: {
    function: "0x1::shapes::draw_point",
    functionArguments: [pointArg],
  },
});

// Example 2: Nested structs
const lineType = parseTypeTag("0x1::shapes::Line") as TypeTagStruct;
const lineArg = await parser.encodeStructArgument(lineType, {
  start: { x: "0", y: "0" },
  end: { x: "10", y: "10" }
});

const transaction2 = await aptos.transaction.build.simple({
  sender: alice.accountAddress,
  data: {
    function: "0x1::shapes::draw_line",
    functionArguments: [lineArg],
  },
});

// Example 3: Enum variants
const colorType = parseTypeTag("0x1::game::Color") as TypeTagStruct;
const colorArg = await parser.encodeEnumArgument(colorType, { Red: {} });

const transaction3 = await aptos.transaction.build.simple({
  sender: alice.accountAddress,
  data: {
    function: "0x1::game::set_color",
    functionArguments: [colorArg],
  },
});

// Example 4: Enum with fields
const accountTypeTag = parseTypeTag("0x1::game::AccountType") as TypeTagStruct;
const accountTypeArg = await parser.encodeEnumArgument(accountTypeTag, {
  Premium: { "0": "100" }
});

const transaction4 = await aptos.transaction.build.simple({
  sender: alice.accountAddress,
  data: {
    function: "0x1::game::create_player",
    functionArguments: [accountTypeArg],
  },
});

Features:

  • Support for nested structs/enums (up to 7 levels deep)
  • Generic type parameter substitution (T0, T1, etc.)
  • All Move primitive types (bool, u8-u256, i8-i256, address)
  • Special framework types (String, Object, Option)
  • Option dual format support (vector []/[value] or enum {None:{}}/{Some:{0:value}})
  • Module ABI caching for performance

Troubleshooting

If you see an import error when you do this:

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

Make sure your tsconfig.json uses a compatible moduleResolution setting. The SDK is ESM-only and works with "nodenext", "node16", or "bundler" module resolution.

Contributing

If you found a bug or would like to request a feature, please file an issue. If, based on the discussion on an issue, you would like to offer a code change, please make a pull request. If neither of these describes what you would like to contribute, check out the contributing guide.

Running unit tests

pnpm --filter @aptos-labs/ts-sdk test                                      # Run all tests (unit + e2e)
pnpm --filter @aptos-labs/ts-sdk exec vitest run tests/unit                # Run unit tests only
pnpm --filter @aptos-labs/ts-sdk exec vitest run tests/unit/keyless.test.ts # Run a specific test file

版本与发布记录

@aptos-labs/ts-sdk 共发布 207 个版本,首次发布于 2023/10/19;过去 12 个月发布了 23 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
7.5.0latest2026/10/1029 天前
7.4.02026/10/061 个月前
7.3.02026/08/112 个月前
7.2.02026/07/074 个月前
7.2.0-beta.02026/06/254 个月前
7.1.32026/06/244 个月前

其他发布通道:experimental → 0.0.8,plugin → 1.9.1-plugin.23,win → 1.15.0-win.2,tmp → 1.9.1-tmp.4,sc → 1.33.2-sc.0,zeta → 4.0.0-zeta.0。

关于 @aptos-labs/ts-sdk 的常见问题

@aptos-labs/ts-sdk 是什么?

Aptos TypeScript SDK

如何安装 @aptos-labs/ts-sdk?

在项目目录运行 npm install @aptos-labs/ts-sdk,或使用 pnpm add / yarn add / bun add。

@aptos-labs/ts-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@aptos-labs/ts-sdk 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@aptos-labs/ts-sdk 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@aptos-labs/ts-sdk 可以商用吗?

@aptos-labs/ts-sdk 使用 SEE LICENSE IN LICENSE 许可。许可条款写在包内的独立文件中,请阅读该文件确认可否商用。以上为概括,不构成法律意见,请以许可原文为准。

@aptos-labs/ts-sdk 的下载量有多少?

根据 npm 官方下载统计,@aptos-labs/ts-sdk 在 2026/10/07 – 2026/11/05 这 30 天内被下载 676,217 次,日均约 22,541 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@aptos-labs/ts-sdk 还在维护吗?

最新版本 7.5.0 发布于 2026/10/10(29 天前);至今共发布 207 个版本,其中过去 12 个月发布了 23 个;首次发布于 2023/10/19。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。