use-ts-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Use TypeScript SDK (Orchestrator)

使用TypeScript SDK(协调器)

Purpose

用途

Orchestrates
@aptos-labs/ts-sdk
integration for Aptos dApps. For specific tasks, route to the appropriate granular skill. For composite tasks (e.g., "build me a fullstack dApp"), follow the workflow below.
协调Aptos dApp与
@aptos-labs/ts-sdk
的集成。针对特定任务,路由到对应的细分技能。对于复合任务(例如“帮我构建一个全栈dApp”),请遵循以下工作流程。

Core Rules

核心规则

  1. ALWAYS use
    @aptos-labs/ts-sdk
    (the current official SDK, NOT the deprecated
    aptos
    package)
  2. NEVER hardcode private keys in source code or frontend bundles
  3. NEVER expose private keys in client-side code or logs
  4. NEVER store private keys in environment variables accessible to the browser (use
    VITE_
    prefix only for public config)
  5. ALWAYS load private keys from environment variables in server-side scripts only, using
    process.env
  1. 始终使用
    @aptos-labs/ts-sdk
    (当前官方SDK,而非已弃用的
    aptos
    包)
  2. 绝对不要在源代码或前端包中硬编码私钥
  3. 绝对不要在客户端代码或日志中暴露私钥
  4. 绝对不要将私钥存储在浏览器可访问的环境变量中(仅对公共配置使用
    VITE_
    前缀)
  5. 仅在服务器端脚本中从环境变量加载私钥,使用
    process.env

Important: Boilerplate Template

重要提示:模板项目

If the project was scaffolded with
create-aptos-dapp
(boilerplate template), wallet adapter and SDK setup are already done. Before writing new code, check what already exists:
  • frontend/components/WalletProvider.tsx
    — wallet adapter setup with auto-connect
  • frontend/constants.ts
    NETWORK
    ,
    MODULE_ADDRESS
    ,
    APTOS_API_KEY
    from env vars
  • frontend/entry-functions/
    — existing entry function patterns (follow these for new ones)
  • frontend/view-functions/
    — existing view function patterns (follow these for new ones)
Do NOT recreate wallet provider, client setup, or constants if they already exist. Instead, follow the existing patterns to add new entry/view functions for your Move contracts.
如果项目是通过
create-aptos-dapp
(模板项目)搭建的,钱包适配器和SDK设置已完成。在编写新代码之前,请检查现有内容:
  • frontend/components/WalletProvider.tsx
    — 带自动连接功能的钱包适配器设置
  • frontend/constants.ts
    — 来自环境变量的
    NETWORK
    MODULE_ADDRESS
    APTOS_API_KEY
  • frontend/entry-functions/
    — 现有入口函数模式(新增时遵循此模式)
  • frontend/view-functions/
    — 现有视图函数模式(新增时遵循此模式)
请勿重复创建钱包提供者、客户端设置或常量。请遵循现有模式为你的Move合约添加新的入口/视图函数。

Skill Routing

技能路由

Route to the appropriate granular skill based on the task:
TaskSkill
Set up Aptos client / configure networkts-sdk-client
Create accounts/signers (server-side)ts-sdk-account
Parse, format, or derive addressests-sdk-address
Build, sign, submit, simulate transactionsts-sdk-transactions
Read on-chain data (view, balances, resources)ts-sdk-view-and-query
Map Move types to TypeScript typests-sdk-types
Connect wallet in React frontendts-sdk-wallet-adapter
根据任务路由到对应的细分技能:
任务技能
设置Aptos客户端/配置网络ts-sdk-client
创建账户/签名者(服务器端)ts-sdk-account
解析、格式化或派生地址ts-sdk-address
构建、签名、提交、模拟交易ts-sdk-transactions
读取链上数据(视图、余额、资源)ts-sdk-view-and-query
将Move类型映射到TypeScript类型ts-sdk-types
在React前端中连接钱包ts-sdk-wallet-adapter

Fullstack dApp Workflow

全栈dApp工作流程

When building a complete frontend integration:
  1. Set up client → read ts-sdk-client
  2. Create view function wrappers → read ts-sdk-view-and-query
  3. Create entry function payloads → read ts-sdk-transactions
  4. Wire up wallet connection → read ts-sdk-wallet-adapter
  5. Handle types correctly → read ts-sdk-types (as needed)
构建完整的前端集成时:
  1. 设置客户端 → 阅读ts-sdk-client
  2. 创建视图函数包装器 → 阅读ts-sdk-view-and-query
  3. 创建入口函数负载 → 阅读ts-sdk-transactions
  4. 连接钱包 → 阅读ts-sdk-wallet-adapter
  5. 正确处理类型 → 阅读ts-sdk-types(按需使用)

File Organization Pattern

文件组织模式

src/
  lib/
    aptos.ts                    # Singleton Aptos client + MODULE_ADDRESS
  view-functions/
    getCount.ts                 # One file per view function
    getListing.ts
  entry-functions/
    increment.ts                # One file per entry function
    createListing.ts
  hooks/
    useCounter.ts               # React hooks wrapping view functions
    useListing.ts
  components/
    WalletProvider.tsx           # AptosWalletAdapterProvider wrapper
    IncrementButton.tsx          # Components calling entry functions
src/
  lib/
    aptos.ts                    # 单例Aptos客户端 + MODULE_ADDRESS
  view-functions/
    getCount.ts                 # 每个视图函数对应一个文件
    getListing.ts
  entry-functions/
    increment.ts                # 每个入口函数对应一个文件
    createListing.ts
  hooks/
    useCounter.ts               # 包装视图函数的React钩子
    useListing.ts
  components/
    WalletProvider.tsx           # AptosWalletAdapterProvider包装器
    IncrementButton.tsx          # 调用入口函数的组件

Error Handling Pattern

错误处理模式

typescript
async function submitTransaction(
  aptos: Aptos,
  signer: Account,
  payload: InputGenerateTransactionPayloadData
): Promise<string> {
  try {
    const transaction = await aptos.transaction.build.simple({
      sender: signer.accountAddress,
      data: payload
    });

    const pendingTx = await aptos.signAndSubmitTransaction({
      signer,
      transaction
    });

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

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

    return pendingTx.hash;
  } catch (error) {
    if (error instanceof Error) {
      if (error.message.includes("RESOURCE_NOT_FOUND")) {
        throw new Error("Resource does not exist at the specified address");
      }
      if (error.message.includes("MODULE_NOT_FOUND")) {
        throw new Error("Contract is not deployed at the specified address");
      }
      if (error.message.includes("ABORTED")) {
        const match = error.message.match(/code: (\d+)/);
        const code = match ? match[1] : "unknown";
        throw new Error(`Contract error (code ${code})`);
      }
    }
    throw error;
  }
}
typescript
async function submitTransaction(
  aptos: Aptos,
  signer: Account,
  payload: InputGenerateTransactionPayloadData
): Promise<string> {
  try {
    const transaction = await aptos.transaction.build.simple({
      sender: signer.accountAddress,
      data: payload
    });

    const pendingTx = await aptos.signAndSubmitTransaction({
      signer,
      transaction
    });

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

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

    return pendingTx.hash;
  } catch (error) {
    if (error instanceof Error) {
      if (error.message.includes("RESOURCE_NOT_FOUND")) {
        throw new Error("指定地址的资源不存在");
      }
      if (error.message.includes("MODULE_NOT_FOUND")) {
        throw new Error"指定地址未部署合约");
      }
      if (error.message.includes("ABORTED")) {
        const match = error.message.match(/code: (\d+)/);
        const code = match ? match[1] : "unknown";
        throw new Error(`合约错误(代码 ${code}`);
      }
    }
    throw error;
  }
}

Edge Cases

边缘场景

ScenarioCheckAction
Resource not found
error.message.includes("RESOURCE_NOT_FOUND")
Return default value or null
Module not deployed
error.message.includes("MODULE_NOT_FOUND")
Show "contract not deployed" message
Function not found
error.message.includes("FUNCTION_NOT_FOUND")
Check function name and module address
Move abort
error.message.includes("ABORTED")
Parse abort code, map to user-friendly error
Out of gas
error.message.includes("OUT_OF_GAS")
Increase
maxGasAmount
and retry
Sequence number error
error.message.includes("SEQUENCE_NUMBER")
Retry after fetching fresh sequence number
Network timeout
error.message.includes("timeout")
Retry with exponential backoff
Account does not exist
error.message.includes("ACCOUNT_NOT_FOUND")
Fund account or prompt user to create one
Insufficient balance
error.message.includes("INSUFFICIENT_BALANCE")
Show balance and required amount
User rejected in walletWallet-specific rejection errorShow "transaction cancelled" message
场景检查项处理操作
资源不存在
error.message.includes("RESOURCE_NOT_FOUND")
返回默认值或null
模块未部署
error.message.includes("MODULE_NOT_FOUND")
显示“合约未部署”提示
函数不存在
error.message.includes("FUNCTION_NOT_FOUND")
检查函数名称和模块地址
Move中止
error.message.includes("ABORTED")
解析中止代码,转换为用户友好的错误提示
燃气不足
error.message.includes("OUT_OF_GAS")
增加
maxGasAmount
并重试
序列号错误
error.message.includes("SEQUENCE_NUMBER")
获取最新序列号后重试
网络超时
error.message.includes("timeout")
使用指数退避策略重试
账户不存在
error.message.includes("ACCOUNT_NOT_FOUND")
为账户充值或提示用户创建账户
余额不足
error.message.includes("INSUFFICIENT_BALANCE")
显示当前余额和所需金额
用户在钱包中拒绝交易钱包特定的拒绝错误显示“交易已取消”提示

Anti-patterns

反模式

  1. NEVER use the deprecated
    aptos
    npm package
    — use
    @aptos-labs/ts-sdk
  2. NEVER skip
    waitForTransaction
    after submitting — transaction may not be committed yet
  3. NEVER hardcode module addresses — use environment variables (
    VITE_MODULE_ADDRESS
    )
  4. NEVER create multiple
    Aptos
    client instances
    — create one singleton and share it
  5. NEVER use
    Account.generate()
    in frontend code
    for real users — use wallet adapter
  6. NEVER use
    scriptComposer
    — removed in v6.0; use separate transactions instead
  7. NEVER use
    getAccountCoinAmount
    or
    getAccountAPTAmount
    — deprecated; use
    getBalance()
  1. 绝对不要使用已弃用的
    aptos
    npm包
    — 使用
    @aptos-labs/ts-sdk
  2. 提交交易后绝对不要跳过
    waitForTransaction
    — 交易可能尚未完成上链
  3. 绝对不要硬编码模块地址 — 使用环境变量(
    VITE_MODULE_ADDRESS
  4. 绝对不要创建多个
    Aptos
    客户端实例
    — 创建一个单例并共享使用
  5. 绝对不要在前端代码中为真实用户使用
    Account.generate()
    — 使用钱包适配器
  6. 绝对不要使用
    scriptComposer
    — v6.0已移除;请改用单独的交易
  7. 绝对不要使用
    getAccountCoinAmount
    getAccountAPTAmount
    — 已弃用;使用
    getBalance()

SDK Version Notes

SDK版本说明

AIP-80 Private Key Format (v2.0+)

AIP-80私钥格式(v2.0+)

Ed25519 and Secp256k1 private keys now use an AIP-80 prefixed format when serialized with
toString()
:
typescript
const key = new Ed25519PrivateKey("0x...");
key.toString(); // Returns AIP-80 prefixed format, NOT raw hex
Ed25519和Secp256k1私钥现在在使用
toString()
序列化时采用AIP-80前缀格式:
typescript
const key = new Ed25519PrivateKey("0x...");
key.toString(); // 返回AIP-80前缀格式,而非原始十六进制

Fungible Asset Transfers (v1.39+)

fungible资产转账(v1.39+)

typescript
await aptos.transferFungibleAssetBetweenStores({
  sender: account,
  fungibleAssetMetadataAddress: metadataAddr,
  senderStoreAddress: fromStore,
  recipientStoreAddress: toStore,
  amount: 1000n
});
typescript
await aptos.transferFungibleAssetBetweenStores({
  sender: account,
  fungibleAssetMetadataAddress: metadataAddr,
  senderStoreAddress: fromStore,
  recipientStoreAddress: toStore,
  amount: 1000n
});

Account Abstraction (v1.34+, AIP-104)

账户抽象(v1.34+,AIP-104)

typescript
// Check if AA is enabled for an account
const isEnabled = await aptos.abstraction.isAccountAbstractionEnabled({
  accountAddress: "0x...",
  authenticationFunction: `${MODULE_ADDRESS}::auth::authenticate`
});

// Enable AA on an account
const enableTxn = await aptos.abstraction.enableAccountAbstractionTransaction({
  accountAddress: account.accountAddress,
  authenticationFunction: `${MODULE_ADDRESS}::auth::authenticate`
});

// Use AbstractedAccount for signing with custom auth logic
import { AbstractedAccount } from "@aptos-labs/ts-sdk";
typescript
// 检查账户是否启用了AA
const isEnabled = await aptos.abstraction.isAccountAbstractionEnabled({
  accountAddress: "0x...",
  authenticationFunction: `${MODULE_ADDRESS}::auth::authenticate`
});

// 为账户启用AA
const enableTxn = await aptos.abstraction.enableAccountAbstractionTransaction({
  accountAddress: account.accountAddress,
  authenticationFunction: `${MODULE_ADDRESS}::auth::authenticate`
});

// 使用AbstractedAccount通过自定义认证逻辑签名
import { AbstractedAccount } from "@aptos-labs/ts-sdk";

References

参考资料

Pattern Documentation:
  • TYPESCRIPT_SDK.md — Complete SDK API reference
Official Documentation:
Granular Skills:
  • ts-sdk-client — Client setup and configuration
  • ts-sdk-account — Account/signer creation
  • ts-sdk-address — Address parsing and derivation
  • ts-sdk-transactions — Build, sign, submit transactions
  • ts-sdk-view-and-query — View functions and queries
  • ts-sdk-types — Move-to-TypeScript type mapping
  • ts-sdk-wallet-adapter — React wallet integration
Related Skills:
  • write-contracts
    — Write the Move contracts that this SDK interacts with
  • deploy-contracts
    — Deploy contracts before calling them from TypeScript
模式文档:
  • TYPESCRIPT_SDK.md — 完整SDK API参考
官方文档:
细分技能:
  • ts-sdk-client — 客户端设置和配置
  • ts-sdk-account — 账户/签名者创建
  • ts-sdk-address — 地址解析和派生
  • ts-sdk-transactions — 构建、签名、提交交易
  • ts-sdk-view-and-query — 视图函数和查询
  • ts-sdk-types — Move到TypeScript的类型映射
  • ts-sdk-wallet-adapter — React钱包集成
相关技能:
  • write-contracts
    — 编写本SDK交互的Move合约
  • deploy-contracts
    — 从TypeScript调用合约前部署合约