Aptos 的脚本 SDK 类型
这个 类型脚本 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