Use TypeScript SDK (Orchestrator)
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.
Core Rules
- 1. ALWAYS use
@aptos-labs/ts-sdk (the current official SDK, NOT the deprecated aptos package) - NEVER hardcode private keys in source code or frontend bundles
- NEVER expose private keys in client-side code or logs
- 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 INLINECODE4
Important: Boilerplate Template
If the project was scaffolded with npx 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 - INLINECODE7 —
NETWORK, MODULE_ADDRESS, APTOS_API_KEY from env vars - INLINECODE11 — existing entry function patterns (follow these for new ones)
- INLINECODE12 — 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.
Skill Routing
Route to the appropriate granular skill based on the task:
| Task | Skill |
|---|
| Set up Aptos client / configure network | ts-sdk-client |
| Create accounts/signers (server-side) |
ts-sdk-account |
| Parse, format, or derive addresses |
ts-sdk-address |
| Build, sign, submit, simulate transactions |
ts-sdk-transactions |
| Read on-chain data (view, balances, resources) |
ts-sdk-view-and-query |
| Map Move types to TypeScript types |
ts-sdk-types |
| Connect wallet in React frontend |
ts-sdk-wallet-adapter |
Fullstack dApp Workflow
When building a complete frontend integration:
- 1. Set up client → read ts-sdk-client
- Create view function wrappers → read ts-sdk-view-and-query
- Create entry function payloads → read ts-sdk-transactions
- Wire up wallet connection → read ts-sdk-wallet-adapter
- Handle types correctly → read ts-sdk-types (as needed)
File Organization Pattern
CODEBLOCK0
Error Handling Pattern
CODEBLOCK1
Edge Cases
| Scenario | Check | Action |
|---|
| Resource not found | INLINECODE13 | 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 wallet | Wallet-specific rejection error | Show "transaction cancelled" message |
Anti-patterns
- 1. NEVER use the deprecated
aptos npm package — use INLINECODE24 - NEVER skip
waitForTransaction after submitting — transaction may not be committed yet - NEVER hardcode module addresses — use environment variables (
VITE_MODULE_ADDRESS) - NEVER create multiple
Aptos client instances — create one singleton and share it - NEVER use
Account.generate() in frontend code for real users — use wallet adapter - NEVER use
scriptComposer — removed in v6.0; use separate transactions instead - NEVER use
getAccountCoinAmount or getAccountAPTAmount — deprecated; use INLINECODE32
SDK Version Notes
AIP-80 Private Key Format (v2.0+)
Ed25519 and Secp256k1 private keys now use an AIP-80 prefixed format when serialized with toString():
CODEBLOCK2
Fungible Asset Transfers (v1.39+)
CODEBLOCK3
Account Abstraction (v1.34+, AIP-104)
CODEBLOCK4
References
Pattern Documentation:
Official Documentation:
- - TypeScript SDK: https://aptos.dev/build/sdks/ts-sdk
- API Reference: https://aptos-labs.github.io/aptos-ts-sdk/
- Wallet Adapter: https://aptos.dev/build/sdks/wallet-adapter/dapp
- GitHub: https://github.com/aptos-labs/aptos-ts-sdk
Granular Skills:
Related Skills:
- -
write-contracts — Write the Move contracts that this SDK interacts with - INLINECODE35 — Deploy contracts before calling them from TypeScript
使用TypeScript SDK(编排器)
目的
为Aptos dApp编排@aptos-labs/ts-sdk集成。对于特定任务,路由到相应的细粒度技能。对于复合任务(例如为我构建一个全栈dApp),请遵循以下工作流程。
核心规则
- 1. 始终使用@aptos-labs/ts-sdk(当前官方SDK,而非已弃用的aptos包)
- 切勿在源代码或前端包中硬编码私钥
- 切勿在客户端代码或日志中暴露私钥
- 切勿在浏览器可访问的环境变量中存储私钥(仅对公共配置使用VITE_前缀)
- 仅在服务端脚本中使用process.env从环境变量加载私钥
重要:样板模板
如果项目使用npx create-aptos-dapp(样板模板)搭建,钱包适配器和SDK设置已完成。在编写新代码前,检查已存在的内容:
- - frontend/components/WalletProvider.tsx — 带自动连接功能的钱包适配器设置
- frontend/constants.ts — 来自环境变量的NETWORK、MODULEADDRESS、APTOSAPI_KEY
- frontend/entry-functions/ — 现有的入口函数模式(新函数遵循这些模式)
- frontend/view-functions/ — 现有的视图函数模式(新函数遵循这些模式)
不要重新创建已存在的钱包提供者、客户端设置或常量。相反,遵循现有模式为你的Move合约添加新的入口/视图函数。
技能路由
根据任务路由到相应的细粒度技能:
ts-sdk-account |
| 解析、格式化或推导地址 |
ts-sdk-address |
| 构建、签名、提交、模拟交易 |
ts-sdk-transactions |
| 读取链上数据(视图、余额、资源) |
ts-sdk-view-and-query |
| 将Move类型映射到TypeScript类型 |
ts-sdk-types |
| 在React前端连接钱包 |
ts-sdk-wallet-adapter |
全栈dApp工作流程
构建完整的前端集成时:
- 1. 设置客户端 → 阅读ts-sdk-client
- 创建视图函数包装器 → 阅读ts-sdk-view-and-query
- 创建入口函数负载 → 阅读ts-sdk-transactions
- 连接钱包 → 阅读ts-sdk-wallet-adapter
- 正确处理类型 → 阅读ts-sdk-types(按需)
文件组织模式
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 # 调用入口函数的组件
错误处理模式
typescript
async function submitTransaction(
aptos: Aptos,
signer: Account,
payload: InputGenerateTransactionPayloadData
): Promise {
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(交易失败: ${committed.vm_status});
}
return pendingTx.hash;
} catch (error) {
if (error instanceof Error) {
if (error.message.includes(RESOURCENOTFOUND)) {
throw new Error(指定地址不存在该资源);
}
if (error.message.includes(MODULENOTFOUND)) {
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;
}
}
边界情况
| 场景 | 检查 | 操作 |
|---|
| 资源未找到 | error.message.includes(RESOURCENOTFOUND) | 返回默认值或null |
| 模块未部署 |
error.message.includes(MODULE
NOTFOUND) | 显示合约未部署消息 |
| 函数未找到 | error.message.includes(FUNCTION
NOTFOUND) | 检查函数名称和模块地址 |
| Move中止 | error.message.includes(ABORTED) | 解析中止代码,映射为用户友好的错误信息 |
| Gas耗尽 | error.message.includes(OUT
OFGAS) | 增加maxGasAmount并重试 |
| 序列号错误 | error.message.includes(SEQUENCE_NUMBER) | 获取最新序列号后重试 |
| 网络超时 | error.message.includes(timeout) | 使用指数退避重试 |
| 账户不存在 | error.message.includes(ACCOUNT
NOTFOUND) | 为账户充值或提示用户创建账户 |
| 余额不足 | error.message.includes(INSUFFICIENT_BALANCE) | 显示余额和所需金额 |
| 用户在钱包中拒绝 | 钱包特定的拒绝错误 | 显示交易已取消消息 |
反模式
- 1. 切勿使用已弃用的aptos npm包 — 使用@aptos-labs/ts-sdk
- 提交后切勿跳过waitForTransaction — 交易可能尚未提交
- 切勿硬编码模块地址 — 使用环境变量(VITEMODULEADDRESS)
- 切勿创建多个Aptos客户端实例 — 创建一个单例并共享
- 切勿在前端代码中对真实用户使用Account.generate() — 使用钱包适配器
- 切勿使用scriptComposer — 已在v6.0中移除;改用单独的交易
- 切勿使用getAccountCoinAmount或getAccountAPTAmount — 已弃用;使用getBalance()
SDK版本说明
AIP-80私钥格式(v2.0+)
Ed25519和Secp256k1私钥在使用toString()序列化时现在使用AIP-80前缀格式:
typescript
const key = new Ed25519PrivateKey(0x...);
key.toString(); // 返回AIP-80前缀格式,而非原始十六进制
可替代资产转账(v1.39+)
typescript
await aptos.transferFungibleAssetBetweenStores({
sender: account,
fungibleAssetMetadataAddress: metadataAddr,
senderStoreAddress: fromStore,
recipientStoreAddress: toStore,
amount: 1000n
});
账户抽象(v1.34+,AIP-104)
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;
参考资料
模式文档: