@aptos-labs/ts-sdk

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

Aptos 类型脚本 SDK

中文使用文档
文档目录16 节
  1. 学习更多
  2. 安装
  3. 用于Node.js或网络应用程序
  4. 与 Bun 一起使用
  5. 用于浏览器
  6. 使用量
  7. 备选案文1: Aptos 类(全一)
  8. 备选案文2:次路径的命名空间类(树木可移动)
  9. 备选办法3:独立的功能(最大震动树)
  10. 从 Onchain 读取数据( 指南 (中文(简体) )
  11. 账户管理( 默认为 Ed25519)
  12. 提交交易( E) 教学 (中文(简体) )
  13. 使用 Struct 和 Enum 参数
  14. 解决问题
  15. 捐款
  16. 运行单元测试

Aptos 的脚本 SDK 类型

NPM Package Version Node Version NPM Package Downloads

这个 类型脚本 SDK 允许您与 Aptos 块链连接、探索和互动。 你可以用它来请求数据,发送交易,设置测试环境,以及更多!

学习更多

综合指南、辅导和API参考,访问 aptos.dev (英语)数字 :

安装

用于Node.js或网络应用程序

安装您最喜欢的软件包管理器, 如 npm、 纱线或 pnpm :

pnpm install @aptos-labs/ts-sdk

与 Bun 一起使用

SDK是兼容的 阿宝 运行时间。 使用 Bun 软件包管理器安装 SDK :

bun add @aptos-labs/ts-sdk

用于浏览器

SDK只采用无害环境管理,并与任何现代捆绑商(Vite,webpack等)合作:

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

使用量

备选案文1: Aptos 类(全一)

最简单的开始方式 不是可树摇动的——拉入所有子模块.

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

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

备选案文2:次路径的命名空间类(树木可移动)

仅导入您需要的带有完整自动完成的更小捆绑的命名空间 :

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);

备选办法3:独立的功能(最大震动树)

对于最小可能的捆绑(例如钱包适配器),导入独立的 函数来自其子路径. AptosConfig 编号 : Network 还提供 他们的子道@aptos-labs/ts-sdk/general,但从 主桶很好——包被标记 sideEffects: false如此现代 捆绑者仍然未使用出口树摇.

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 });

从 Onchain 读取数据(指南(中文(简体) )


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

读取已记录的历史

公共全节点只保留了近代历史的滚动窗口. 窗口外的读取失败 410 Gone 还有一个 archival_endpoint 命名一个仍然保存数据的节点。 SDK重复了那些读取的端点和 以透明方式返回结果,所以历史查询继续工作,无需更改代码.

证书只有在与你配置的节点在同一站点时才送交档案端点 终点由节点而不是由您选择。 要禁用重试 :

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

说明: getTransactionByHash 未覆盖。 一个被套取的节点无法从一个从未套取过的交易中分辨一个被套取过的交易 存在,所以它回答 404 没有存档提示。 使用 getTransactionByVersion 用于历史检索,或点 fullnode 直接在一个档案端点.

账户管理( 默认为 Ed25519)

注:我们引入了单一发件人认证(如 AIP-55 (英语)) (中文(简体) ). 生成一个账户默认值为Legacy Ed25519认证,可选择使用"单一发件人"统一认证.


生成新密钥

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

来自私钥

// 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 });

来源于私钥和地址

// 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 });

从路径衍生

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

提交交易( E)教学(中文(简体) )


/**
 * 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();

使用 Struct 和 Enum 参数


SDK支持通过公共副本 structs和enums作为交易参数. 您必须使用 StructEnumArgumentParser 用于交易构建功能之前:

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],
  },
});

特征 :

  • 支持嵌入式结构(深可达7级)
  • 通用类型参数替代 (T0, T1等)
  • 所有移动原始类型(bool,u8-u256,i8-i256,地址)
  • 特殊框架类型(结构、对象、选项)
  • 选项双格式支持(种子) []编号 :[value] 或矿井 {None:{}}编号 :{Some:{0:value}}(中文(简体) )
  • 模块 ABI 缓存性能

解决问题

如果您在这样做时看到导入出错 :

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

保证你 tsconfig.json 使用兼容 moduleResolution 设置。 SDK只采用无害环境管理,并与 "nodenext", (中文(简体) ), "node16",或 "bundler" 模块分辨率.

捐款

如果您发现错误或想要请求特性, 请存档 问题。 。 。 . 如果根据对某一问题的讨论,你想提出更改代码,请作出 拉动请求。 。 。 . 如果两者都未说明你愿意贡献什么,请检查 贡献指南。 。 。 .

运行单元测试

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 类型脚本 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 和提交记录判断。