Token导航 LogoToken导航TokenDH.com
前端设计敏感数据github未标认证来源可访问许可证需确认审计提醒

use-typescript-sdkUSE TypeScript SDK 命令行

Agent Skill

use-typescript-sdk 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

282

周安装

12

GitHub Stars

12

下载量

99
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:use-typescript-sdk(USE TypeScript SDK 命令行)
来源仓库:https://github.com/iskysun96/aptos-agent-skills
仓库路径:skills/use-typescript-sdk
安装命令:
npx skills add https://github.com/iskysun96/aptos-agent-skills --skill use-typescript-sdk
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/iskysun96/aptos-agent-skills --skill use-typescript-sdk

简介

use-typescript-sdk 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态或协作事项进行整理时使用。

  • 适用于 TypeScript 项目相关的代码管理与协作流程支持。
  • 可自动提取仓库元数据、变更记录和协作动态并结构化输出。
  • 安装命令为 npx skills add https://github.com/iskysun96/aptos-agent-skills --skill use-typescript-sdk。
  • 使用前请确认权限范围、维护状态及是否涉及文件读写或网络请求。

SKILL.md

Use TypeScript SDK Skill

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.tsNETWORK, 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)
  • frontend/components/ — working components (TransferAPT, MessageBoard, WalletSelector, etc.)

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.

Core Rules

SDK Setup

  1. ALWAYS use @aptos-labs/ts-sdk (the current official SDK, NOT the deprecated aptos package)
  2. ALWAYS create a singleton Aptos client and export it from a shared module (e.g., lib/aptos.ts)
  3. ALWAYS configure the network via AptosConfig with environment variables
  4. ALWAYS use Network.TESTNET as the default for development (NOT devnet, which resets frequently)

Balance & Queries

  1. ALWAYS use aptos.getBalance() for APT balance queries (NOT the deprecated getAccountCoinAmount or getAccountAPTAmount)

Transactions

  1. ALWAYS call waitForTransaction after submitting any transaction
  2. ALWAYS simulate transactions before submitting for critical or high-value operations
  3. ALWAYS wrap blockchain calls in try/catch with specific error handling
  4. ALWAYS use the build-sign-submit pattern: transaction.build.simple() then signAndSubmitTransaction()

Security

  1. NEVER hardcode private keys in source code or frontend bundles
  2. NEVER expose private keys in client-side code or logs
  3. NEVER store private keys in environment variables accessible to the browser (use VITE_ prefix only for public config)
  4. ALWAYS load private keys from environment variables in server-side scripts only, using process.env

Type Safety

  1. ALWAYS use bigint for u128 and u256 values (JavaScript number loses precision)
  2. ALWAYS pass Object<T> references as address strings in functionArguments
  3. ALWAYS use typed entry/view function wrappers instead of raw string-based calls in production code

Wallet Adapter

  1. ALWAYS use @aptos-labs/wallet-adapter-react for frontend wallet integration
  2. ALWAYS wrap your app with AptosWalletAdapterProvider
  3. ALWAYS use useWallet() hook to access wallet functions in React components

Quick Workflow

  1. Install SDK -> npm install @aptos-labs/ts-sdk
  2. Create client -> Singleton Aptos instance in lib/aptos.ts
  3. Read data -> Use aptos.view() for on-chain reads
  4. Write data -> Use aptos.transaction.build.simple() + aptos.signAndSubmitTransaction()
  5. Connect wallet -> Use @aptos-labs/wallet-adapter-react for frontend dApps
  6. Handle errors -> Wrap all calls in try/catch with error-type checks

Key Example: Client Setup

// lib/aptos.ts - Singleton client (create once, import everywhere)
import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";

function getNetwork(): Network {
  const network = import.meta.env.VITE_APP_NETWORK;
  switch (network) {
    case "mainnet":
      return Network.MAINNET;
    case "testnet":
      return Network.TESTNET;
    case "devnet":
      return Network.DEVNET;
    default:
      return Network.TESTNET;
  }
}

const config = new AptosConfig({ network: getNetwork() });
export const aptos = new Aptos(config);

export const MODULE_ADDRESS = import.meta.env.VITE_MODULE_ADDRESS;

Key Example: View Functions (Read)

// view-functions/getCount.ts
import { aptos, MODULE_ADDRESS } from "../lib/aptos";

export async function getCount(accountAddress: string): Promise<number> {
  const result = await aptos.view({
    payload: {
      function: `${MODULE_ADDRESS}::counter::get_count`,
      functionArguments: [accountAddress]
    }
  });
  return Number(result[0]);
}

// With type arguments
export async function getCoinBalance(accountAddress: string, coinType: string): Promise<bigint> {
  const result = await aptos.view({
    payload: {
      function: "0x1::coin::balance",
      typeArguments: [coinType],
      functionArguments: [accountAddress]
    }
  });
  return BigInt(result[0] as string);
}

// Multiple return values
// Move: public fun get_listing(addr): (address, u64, bool)
export async function getListing(nftAddress: string): Promise<{ seller: string; price: number; isActive: boolean }> {
  const [seller, price, isActive] = await aptos.view({
    payload: {
      function: `${MODULE_ADDRESS}::marketplace::get_listing`,
      functionArguments: [nftAddress]
    }
  });
  return {
    seller: seller as string,
    price: Number(price),
    isActive: isActive as boolean
  };
}

Key Example: Entry Functions (Write) - Server/Script

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

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

// Build transaction
const transaction = await aptos.transaction.build.simple({
  sender: account.accountAddress,
  data: {
    function: `${MODULE_ADDRESS}::counter::increment`,
    functionArguments: []
  }
});

// Sign and submit
const pendingTx = await aptos.signAndSubmitTransaction({
  signer: account,
  transaction
});

// ALWAYS wait for confirmation
const committedTx = await aptos.waitForTransaction({
  transactionHash: pendingTx.hash
});

console.log("Success:", committedTx.success);

Key Example: Entry Functions (Write) - Frontend with Wallet

// entry-functions/increment.ts
import { InputTransactionData } from "@aptos-labs/wallet-adapter-react";
import { MODULE_ADDRESS } from "../lib/aptos";

export function buildIncrementPayload(): InputTransactionData {
  return {
    data: {
      function: `${MODULE_ADDRESS}::counter::increment`,
      functionArguments: [],
    },
  };
}

// Component usage
import { useWallet } from "@aptos-labs/wallet-adapter-react";
import { aptos } from "../lib/aptos";
import { buildIncrementPayload } from "../entry-functions/increment";

function IncrementButton() {
  const { signAndSubmitTransaction } = useWallet();

  const handleClick = async () => {
    try {
      const response = await signAndSubmitTransaction(
        buildIncrementPayload(),
      );
      await aptos.waitForTransaction({
        transactionHash: response.hash,
      });
    } catch (error) {
      console.error("Transaction failed:", error);
    }
  };

  return <button onClick={handleClick}>Increment</button>;
}

Key Example: Wallet Adapter Setup

// main.tsx or App.tsx
import { AptosWalletAdapterProvider } from "@aptos-labs/wallet-adapter-react";
import { Network } from "@aptos-labs/ts-sdk";

function App() {
  return (
    <AptosWalletAdapterProvider
      autoConnect={true}
      dappConfig={{
        network: Network.TESTNET,
      }}
      onError={(error) => console.error("Wallet error:", error)}
    >
      <YourApp />
    </AptosWalletAdapterProvider>
  );
}

// In any child component
import { useWallet } from "@aptos-labs/wallet-adapter-react";

function WalletInfo() {
  const { account, connected, connect, disconnect, wallet, wallets } =
    useWallet();

  if (!connected) {
    return (
      <div>
        {wallets.map((w) => (
          <button key={w.name} onClick={() => connect(w.name)}>
            Connect {w.name}
          </button>
        ))}
      </div>
    );
  }

  return (
    <div>
      <p>Connected: {account?.address}</p>
      <p>Wallet: {wallet?.name}</p>
      <button onClick={disconnect}>Disconnect</button>
    </div>
  );
}

Key Example: Sponsored Transactions (Fee Payer)

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

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

// 1. Build with fee payer flag
const transaction = await aptos.transaction.build.simple({
  sender: sender.accountAddress,
  withFeePayer: true,
  data: {
    function: `${MODULE_ADDRESS}::counter::increment`,
    functionArguments: []
  }
});

// 2. Sender signs
const senderAuth = aptos.transaction.sign({
  signer: sender,
  transaction
});

// 3. Fee payer signs (different method!)
const feePayerAuth = aptos.transaction.signAsFeePayer({
  signer: feePayer,
  transaction
});

// 4. Submit with both signatures
const pendingTx = await aptos.transaction.submit.simple({
  transaction,
  senderAuthenticator: senderAuth,
  feePayerAuthenticator: feePayerAuth
});

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

Key Example: Multi-Agent Transactions

// 1. Build multi-agent transaction
const transaction = await aptos.transaction.build.multiAgent({
  sender: alice.accountAddress,
  secondarySignerAddresses: [bob.accountAddress],
  data: {
    function: `${MODULE_ADDRESS}::escrow::exchange`,
    functionArguments: [itemAddress, paymentAmount]
  }
});

// 2. Each agent signs
const aliceAuth = aptos.transaction.sign({
  signer: alice,
  transaction
});
const bobAuth = aptos.transaction.sign({
  signer: bob,
  transaction
});

// 3. Submit with all signatures
const pendingTx = await aptos.transaction.submit.multiAgent({
  transaction,
  senderAuthenticator: aliceAuth,
  additionalSignersAuthenticators: [bobAuth]
});

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

Type Mappings: Move to TypeScript

Move TypeTypeScript TypeExample
u8number255
u16number65535
u32number4294967295
u64`number \bigint`1000000
u128bigintBigInt("340282366920938463463374607431768211455")
u256bigintBigInt("...")
i8number-128 (Move 2.3+)
i16number-32768 (Move 2.3+)
i32number-2147483648 (Move 2.3+)
i64`number \bigint`Use bigint for large values (Move 2.3+)
i128bigintBigInt("-170141183460469231731687303715884105728")
i256bigintBigInt("...") (Move 2.3+)
boolbooleantrue
addressstring"0x1"
Stringstring"hello"
vector<u8>`Uint8Array \string`new Uint8Array([1,2,3]) or hex string
vector<T>T[][1, 2, 3] for vector<u64>
Object<T>stringObject address as hex string
Option<T>`T \null`Value or null

Transaction Simulation

// Build transaction
const transaction = await aptos.transaction.build.simple({
  sender: account.accountAddress,
  data: {
    function: `${MODULE_ADDRESS}::counter::increment`,
    functionArguments: []
  }
});

// Simulate to check for errors and estimate gas
const [simResult] = await aptos.transaction.simulate.simple({
  signerPublicKey: account.publicKey,
  transaction
});

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

console.log("Gas estimate:", simResult.gas_used);

Gas Profiling

// Profile gas usage of a transaction (useful for optimization)
const gasProfile = await aptos.gasProfile({
  sender: account.accountAddress,
  data: {
    function: `${MODULE_ADDRESS}::module::function_name`,
    functionArguments: []
  }
});

console.log("Gas profile:", gasProfile);

Anti-patterns

  1. NEVER use the deprecated aptos npm package - use @aptos-labs/ts-sdk instead
  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 use number for u128/u256 values - JavaScript loses precision above 2^53; use bigint
  5. NEVER create multiple Aptos client instances - create one singleton and share it
  6. NEVER ignore transaction simulation results for high-value operations
  7. NEVER hardcode network selection - use environment-based configuration
  8. NEVER store private keys in browser-accessible env vars (e.g., VITE_PRIVATE_KEY)
  9. NEVER use Account.generate() in frontend code for real users - use wallet adapter instead
  10. NEVER use raw aptos.signAndSubmitTransaction in React - use the wallet adapter's signAndSubmitTransaction
  11. NEVER use scriptComposer - it was removed in v6.0; use batch transactions or separate calls instead
  12. NEVER use getAccountCoinAmount or getAccountAPTAmount - deprecated; use getBalance() instead

Edge Cases to Handle

ScenarioCheckAction
Resource not founderror.message.includes("RESOURCE_NOT_FOUND")Return default value or null
Module not deployederror.message.includes("MODULE_NOT_FOUND")Show "contract not deployed" message
Function not founderror.message.includes("FUNCTION_NOT_FOUND")Check function name and module address
Move aborterror.message.includes("ABORTED")Parse abort code, map to user-friendly error
Out of gaserror.message.includes("OUT_OF_GAS")Increase maxGasAmount and retry
Sequence number errorerror.message.includes("SEQUENCE_NUMBER")Retry after fetching fresh sequence number
Network timeouterror.message.includes("timeout")Retry with exponential backoff
Account does not existerror.message.includes("ACCOUNT_NOT_FOUND")Fund account or prompt user to create one
Insufficient balanceerror.message.includes("INSUFFICIENT_BALANCE")Show balance and required amount
User rejected in walletWallet-specific rejection errorShow "transaction cancelled" message

Error Handling Pattern

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

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

SDK Version Notes (v5.2+ / v6.0)

Balance Queries (v5.1+)

// CORRECT (v5.1+)
const balance = await aptos.getBalance({
  accountAddress: account.accountAddress
});
// Returns bigint in octas (1 APT = 100_000_000 octas)

// DEPRECATED - do NOT use
// await aptos.getAccountCoinAmount(...)
// await aptos.getAccountAPTAmount(...)

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

Ed25519 and Secp256k1 private keys now use an AIP-80 prefixed format when serialized with toString():

const key = new Ed25519PrivateKey("0x...");
key.toString(); // Returns AIP-80 prefixed format, NOT raw hex

AccountAddress Parsing (v1.32+)

AccountAddress.fromString() now only accepts SHORT format (60-64 hex chars) by default. Use AccountAddress.from() for flexible parsing:

// CORRECT
const addr = AccountAddress.from("0x1"); // Accepts any format
const addr2 = AccountAddress.fromString("0x000000000000000000000000000000000000000000000000000000000000001"); // SHORT format only

// MAY FAIL in v1.32+
// AccountAddress.fromString("0x1") -- too short for SHORT format

Fungible Asset Transfers (v1.39+)

// Transfer between FA stores directly
await aptos.transferFungibleAssetBetweenStores({
  sender: account,
  fungibleAssetMetadataAddress: metadataAddr,
  senderStoreAddress: fromStore,
  recipientStoreAddress: toStore,
  amount: 1000n
});

Bun Runtime Compatibility

When using Bun instead of Node.js, disable HTTP/2 in the client config:

const config = new AptosConfig({
  network: Network.TESTNET,
  clientConfig: { http2: false }
});

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

The aptos.abstraction namespace provides APIs for custom authentication:

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

// Disable AA
const disableTxn = await aptos.abstraction.disableAccountAbstractionTransaction({
  accountAddress: account.accountAddress,
  authenticationFunction: `${MODULE_ADDRESS}::auth::authenticate`
});

// Use AbstractedAccount for signing with custom auth logic
import { AbstractedAccount } from "@aptos-labs/ts-sdk";

References

Detailed Patterns (references/ folder):

  • references/wallet-adapter.md - Wallet adapter setup and patterns
  • references/transaction-patterns.md - Advanced transaction patterns (sponsored, multi-agent, simulation)
  • references/type-mappings.md - Complete Move-to-TypeScript type reference

Pattern Documentation (patterns/ folder):

  • ../../../patterns/fullstack/TYPESCRIPT_SDK.md - Complete SDK API reference

Official Documentation:

Related Skills:

  • write-contracts - Write the Move contracts that this SDK interacts with
  • deploy-contracts - Deploy contracts before calling them from TypeScript

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

34.92%
按下载量换算35

Claude

32.94%
按下载量换算33

Cursor

17.99%
按下载量换算18

Gemini CLI

8.69%
按下载量换算9

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

可疑

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills