@arch-network/arch-sdk

中文文档
0.13.0发布于 2026/11/02MITTypeScriptESM + CJS构建来源已验证近 30 天下载 5919

拱门 SDK

中文使用文档
文档目录34 节
  1. 安装
  2. 快速启动示例
  3. API 概览
  4. 供应商
  5. 信件创建
  6. 签名公用事业
  7. 交易结构
  8. 发送交易
  9. 创建新账户
  10. 类型
  11. 系统指令助手
  12. createAccount
  13. createAccountWithAnchor
  14. transfer
  15. assign
  16. allocate
  17. 程序 SDK 帮助者
  18. 字节
  19. 小端整数
  20. 程序错误
  21. 键
  22. 交易编号
  23. 示例: 创建和发送交易
  24. 高级主题
  25. 解决问题
  26. WebSocket 客户端: 实时事件订阅
  27. 特征
  28. 活动主题
  29. 配置选项
  30. 示例使用
  31. 过滤器
  32. 重新连接
  33. 事件类型
  34. 钱包类型

Arch 类型脚本 SDK

用于在Arch Network上构建,签名和发送交易的TypeScript SDK. 这个SDK为消息创建,签名处理和交易提交提供了低等原始,使开发者能够在Arch协议上构建自定义的工作流程和应用程序.

安装

npm install @arch-network/arch-sdk

快速启动示例

下面是显示如何创建消息,签名,调整签名,以及使用此SDK发送Arch交易的最小示例.

import {
  ArchConnection,
  SanitizedMessageUtil,
  SignatureUtil,
  RpcConnection,
} from '@arch-network/arch-sdk';

// 1. Set up a provider (e.g., RPC connection to an Arch node)
const provider = new RpcConnection({ nodeUrl: 'http://localhost:8899' });
const arch = ArchConnection(provider);

// 2. Prepare your instruction(s) (see Instruction type for structure)
const instructions = [/* ...your instructions here... */];
const payerPubkey = /* Uint8Array (32 bytes) */;
const recentBlockhash = /* Call the archRpc.getBestBlockhash */;

// 3. Create a SanitizedMessage
const message = SanitizedMessageUtil.createSanitizedMessage(
  instructions,
  payerPubkey,
  recentBlockhash
);

// 4. Hash the message and sign it (using your signing method)
const messageHash = SanitizedMessageUtil.hash(message); // Uint8Array

// Decode it using utf-8
const messageHashString = new TextDecoder().decode(messageHash);

// Sign the message hash using your Bitcoin private key, producing a BIP322-compliant signature.
// You can use a wallet or library that supports BIP322 signing.
const signature = bip322Sign(privateKey, messageHashString, addressType); // pseudocode

// 5. Adjust the signature to the required format
const adjustedSignature = SignatureUtil.adjustSignature(signature);

// 6. Build the transaction object
const transaction = {
  version: 0,
  signatures: [adjustedSignature],
  message,
};

// 7. Send the transaction
const txid = await arch.sendTransaction(transaction);
console.log('Arch transaction ID:', txid);

API 概览

供应商

  • Rpc 连接:通过HTTP连接到一个Arch节点.
  • 归档: 扩展一个提供商, 并配备了 Arch 特定的助手( 如创建New Account).

信件创建

  • Sanitized MessageUtil.create Sanitized Message (教程,支付者,最近的 Blockhash) 互联网档案馆的存檔,存档日期2011-12-21
    • 将指令编译为可以签名和发送的犬形信息.
  • 卫生医疗Util.hash(信息)
    • 返回已消毒信件的散列( Uint8Array) 以供签名 .

签名公用事业

  • 签名Util.adjust 签名( 签名: Uint8Array)
    • 将签名规范为 Arch 交易所需的64字节格式.

交易结构

  • 运行时间交易
    • { version: number, signatures: Uint8Array[], message: SanitizedMessage }

发送交易

  • arch.send Transaction(交易:运行时交易):承诺
    • 向 Arch 网络发送交易并返回交易ID.

创建新账户

  • archive.create New Account (): privkey, pubkey, 地址 QQ
    • 生成一个新的键盘并返回地址、 pubkey 和 privkey .

类型

  • 指令数字 : { program_id, accounts, data }
  • 卫生数字 : { header, account_keys, recent_blockhash, instructions }
  • 签署数字 : Uint8Array (64 bytes)
  • 运行时间交易数字 : { version, signatures, message }

系统指令助手

SDK为构建与Arch区块链相兼容的系统指令提供了低级帮助器功能. 这些帮助者以链路 Rust 程序所期望的格式串行指令数据,使得TypeScript的账户容易创建,传输和管理.

createAccount

在块链上创建新账户.

参数:

  • fromPubkey: Pubkey ——资金账户公用钥匙(签名,可写)
  • toPubkey: Pubkey ——新账公用钥匙(签名,可写)
  • lamports: bigint - 转入新账户的灯塔数目
  • space: bigint — 要分配的内存字节数
  • owner: Pubkey - 拥有新账户的方案

示例

const ix = createAccount(funder, newAccount, 1000n, 128n, ownerProgramId);

createAccountWithAnchor

创建新账户并锁定到特定的UTXO(如为比特币集成).

参数:

  • fromPubkey: Pubkey ——资金账户公用钥匙(签名,可写)
  • toPubkey: Pubkey ——新账公用钥匙(签名,可写)
  • lamports: bigint - 需要转移的灯塔数目
  • space: bigint — 要分配的内存字节数
  • owner: Pubkey - 拥有新账户的方案
  • txid: string —— 64 字符串的 UTXO 交易 ID
  • vout: number ——UTXO输出指数

示例

const ix = createAccountWithAnchor(
  funder,
  newAccount,
  1000n,
  128n,
  ownerProgramId,
  'aabbcc...ff', // 64-char hex string
  0,
);

transfer

把灯塔从一个账户转到另一个账户.

参数:

  • fromPubkey: Pubkey ——发件人账户公用钥匙(签名人,可写)
  • toPubkey: Pubkey ——受款人账户公用钥匙(可写)
  • lamports: bigint - 转账数额;必须装入u64(投掷) InvalidArgumentError 以其他方式)

示例

const ix = transfer(sender, recipient, 500n);

assign

为账户指定新的所有者(程序).

参数:

  • pubkey: Pubkey ——改派账户(发件人,可写出)
  • owner: Pubkey ——新所有者程序公钥

示例

const ix = assign(account, newOwnerProgramId);

allocate

在一个账户中分配空间而不为其供资.

参数:

  • pubkey: Pubkey —— 用于分配空间的账户( 签名, 可写)
  • space: bigint — 要分配的字节数

示例

const ix = allocate(account, 256n);

用法说明: 在与这些帮助者一起构建指令后,使用SDK的序列化工具(见上文)进行序列化并发送指令作为交易的一部分.

程序 SDK 帮助者

用于程序SDK的链级构件(账户解码器,指令编码器,出错表). 全部带回 Uint8Array编号 :bigint 并且不需要全球 Buffer。 。 。 .

字节

  • hexToBytes(hex) 编号 : bytesToHex(bytes) - 小写,未加前缀; hexToBytes 修剪,接受两种情况 拒绝奇数长度, 0x 和无hex.
  • bytesToBase58(bytes) 编号 : base58ToBytes(text) 基数58键; base58ToBytes 总是返回32字节并拒绝更长的值.
  • decodeBase64(text) 宽放基础64(atob 语义.
  • asciiBytes(text) 编号 : asciiOf(bytes) ——仅ASCII(PDA种子,账户字符串).
  • bytesEqual(a, b), (中文(简体) ), isHex(value), (中文(简体) ), toByteArray(value) (副本a) Uint8Array 或 JSON 系统 number[]) (中文(简体) ).

小端整数

  • encodeU16LE, (中文(简体) ), encodeU32LE, (中文(简体) ), encodeI32LE (单位:千美元)number和 encodeU64LE, (中文(简体) ), encodeU128LE, (中文(简体) ), encodeI64LE, (中文(简体) ), encodeI128LE (单位:千美元)bigint投掷 InvalidArgumentError 用于该类型以外的一个值,而不是掩盖它.
  • decodeU16LE, (中文(简体) ), decodeU32LE, (中文(简体) ), decodeI32LE (单位:千美元)number, (中文(简体) ), decodeU64LE, (中文(简体) ), decodeU128LE, (中文(简体) ), decodeI64LE, (中文(简体) ), decodeI128LE (单位:千美元)bigint, (中文(简体) ), decodeBool, (中文(简体) ), decodePubkey 带 (data, offset)。 。 。 .

程序错误

import { decodeProgramError, programErrorTable, bytesToHex } from '@arch-network/arch-sdk';

const tables = new Map([
  [bytesToHex(programId), programErrorTable(idl.errors, { decodesWithLogs: false })],
]);
const processed = await rpc.getProcessedTransaction(txid);
decodeProgramError(processed ?? null, tables); // { code, name, message? } | null

decodeProgramError 读取 custom program error: 0xN 从失败状态中查找失败的指令程序 tables (由小写十六进制程序 id 键) 并倾向于匹配 AnchorError 日志行。 除非表格设定 decodesWithLogs,带有日志的失败不解码,因为代码可能来自内置CPI.

键

  • decodeAplMint(data), (中文(简体) ), decodeAplTokenAccount(data), (中文(简体) ), APL_MINT_SIZE (82个), APL_TOKEN_ACCOUNT_SIZE (165); 短数据抛出 MalformedAplAccountError。 。 。 .
  • associatedTokenAddress(owner, mint) —— 说 PubkeyUtil.getAssociatedTokenAddress 允许非曲线所有者.
  • createAssociatedTokenAccountInstruction({ payer, ata, owner, mint }) - 关联的托肯程序 Create (数据) [1](三); ensureAssociatedTokenAccountInstruction(owner, mint) 是自筹资金的形式.
  • tokenTransferInstruction(source, destination, owner, amount) - 标志程序 Transfer (op代码3).

交易编号

  • transactionId(tx: RuntimeTransaction): string 代号: hex(sha256(hex(sha256(serialize(tx)))))。 。 。 .

示例: 创建和发送交易

import {
  ArchConnection,
  SanitizedMessageUtil,
  SignatureUtil,
  RpcConnection,
  // ...other imports
} from '@arch-network/arch-sdk';

// Set up provider and arch connection
const provider = new RpcConnection({ nodeUrl: 'http://localhost:8899' });
const arch = ArchConnection(provider);

// Example instruction (replace with your actual data)
const instruction = {
  program_id: new Uint8Array(32), // 32-byte program ID
  accounts: [
    {
      pubkey: new Uint8Array(32), // 32-byte pubkey
      is_signer: true,
      is_writable: true,
    },
  ],
  data: new Uint8Array([1, 2, 3]), // Your instruction data
};

const payerPubkey = new Uint8Array(32); // Replace with your payer pubkey
const recentBlockhash = '...'; // Call the archRpc.getBestBlockhash

const message = SanitizedMessageUtil.createSanitizedMessage(
  [instruction],
  payerPubkey,
  recentBlockhash,
);

const messageHash = SanitizedMessageUtil.hash(message);
// Sign the message hash with your Bitcoin private key using the BIP322 standard.
// (You must use a wallet or library that supports BIP322 message signing.)
const signature = bip322Sign(privateKey, messageHash, addressType); // pseudocode
const adjustedSignature = SignatureUtil.adjustSignature(signature);

const transaction = {
  version: 0,
  signatures: [adjustedSignature],
  message,
};

const txid = await arch.sendTransaction(transaction);
console.log('Arch transaction ID:', txid);

高级主题

  • 多个签名人: 将多个签名添加到 signatures 交易中的数组.
  • 自定义提供者: 执行 Provider 用于自定义传输或签名逻辑的接口.

解决问题

  • 确保所有公钥和签名分别为32和64字节.
  • 使用 SignatureUtil.adjustSignature 使不同签名库的签名正常化.
  • 如果交易无法发送, 请检查节点连接和块状新鲜度 .

WebSocket 客户端: 实时事件订阅

SDK提供WebSocket客户端,用于订阅来自Arch网络的实时事件,如新块,交易,账户更新等.

特征

  • 连接/断开一个 WebSocket 服务器
  • 订阅事件主题( 块、 交易、 账户更新等)
  • 按自定义标准过滤事件
  • 添加/删除事件的听众
  • 与后退策略自动重联

活动主题

  • block: 新块事件
  • transaction更新交易状态
  • account_update: 账户状态变化
  • rolledback_transactions, (中文(简体) ), reapplied_transactions, (中文(简体) ), dkg: 高级协议活动

配置选项

您可以通过将配置对象传递到构建器来自定义 WebSocket 客户端 :

interface WebSocketClientOptions {
  url: string; // (Required) WebSocket server URL
  maxReconnectAttempts?: number; // Max reconnection attempts (default: 5)
  backoffStrategy?: BackoffStrategy; // Reconnection backoff strategy (see below)
  autoReconnect?: boolean; // Enable auto-reconnect (default: false)
  timeout?: number; // Connection timeout in ms (default: 20000)
  transports?: string[]; // Socket.IO transports (default: ['websocket', 'polling'])
  forceNew?: boolean; // Force new connection (default: true)
  multiplex?: boolean; // Enable multiplexing (default: false)
}

interface BackoffStrategy {
  type: 'constant' | 'linear' | 'exponential'; // Strategy type
  initial?: number; // Initial delay in ms (default: 1000)
  factor?: number; // Growth factor for exponential (default: 2)
  maxDelay?: number; // Max delay in ms (default: 30000)
  step?: number; // Step size for linear (optional)
  jitter?: number; // Jitter as a fraction (default: 0.2)
}

默认 :

  • maxReconnectAttempts: 5个
  • autoReconnect错误
  • timeout编号: 20000
  • transports: ['websocket','polling'] (中文(简体) )
  • forceNew: 真实
  • multiplex错误
  • backoffStrategy: 指向 (初始数:1000ms,因数:2,最大数:延后数:30000ms,焦距:0.2)

示例

const client = new ArchWebSocketClient({
  url: 'ws://localhost:3001',
  autoReconnect: true,
  maxReconnectAttempts: 10,
  timeout: 15000,
  transports: ['websocket'],
  backoffStrategy: {
    type: 'exponential',
    initial: 500,
    factor: 2,
    maxDelay: 20000,
    jitter: 0.1,
  },
});

示例使用

import { ArchWebSocketClient } from '@arch-network/arch-sdk';
import { EventTopic } from '@arch-network/arch-sdk/websocket-client/types/events';

const client = new ArchWebSocketClient({ url: 'ws://localhost:3001' });

// Connect to the server
await client.connect();

// Subscribe to new block events
const blockCallback = async (event) => {
  console.log('New block:', event.hash, event.timestamp);
};
await client.subscribe(EventTopic.Block, blockCallback);

// Subscribe to transaction events with a filter
const txCallback = async (event) => {
  console.log('Transaction update:', event.hash, event.status);
};
await client.subscribe(EventTopic.Transaction, txCallback, {
  status: 'Processed',
});

// Add an additional listener for account updates
client.on(EventTopic.AccountUpdate, (event) => {
  console.log('Account updated:', event.account);
});

// Disconnect when done
await client.disconnect();

过滤器

您可以通过状态,程序ID,块散列等字段过滤事件(参见 EventFilter, (中文(简体) ), TransactionFilter, (中文(简体) ), BlockFilter) (中文(简体) ).

重新连接

客户端支持自动重接自定义的后退策略 :

client.setReconnectOptions(
  true,
  /* strategy */ 'exponential',
  /* maxAttempts */ 5,
);

事件类型

参见所有事件接口的 SDK 源( 例如 ), BlockEvent, (中文(简体) ), TransactionEvent, (中文(简体) ), AccountUpdateEvent) (中文(简体) ).


钱包类型

SDK和相关软件包定义了代表用户钱包、UTXO和集合的类型:

interface Wallet {
  address: string;
  balance: bigint;
  utxos: Array<CollectionUtxo>;
}

interface CollectionUtxo {
  // UTXO details
  collectionStatuses: Array<CollectionAmount>;
  hasInscription: boolean;
}

interface CollectionAmount {
  id: string;
  type: 'rune' | 'btc';
  amount: bigint;
}

这些类型可用于钱包管理,UTXO选择,以及与池或交易逻辑的集成.


版本与发布记录

@arch-network/arch-sdk 共发布 8 个版本,首次发布于 2026/02/18;过去 12 个月发布了 8 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.13.0latest2026/11/025 天前
0.0.312026/10/318 天前
0.0.292026/10/2019 天前
0.0.302026/10/2019 天前
0.0.282026/08/272 个月前
0.0.272026/03/107 个月前

关于 @arch-network/arch-sdk 的常见问题

@arch-network/arch-sdk 是什么?

拱门 SDK

如何安装 @arch-network/arch-sdk?

在项目目录运行 npm install @arch-network/arch-sdk,或使用 pnpm add / yarn add / bun add。

@arch-network/arch-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@arch-network/arch-sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@arch-network/arch-sdk 可以商用吗?

@arch-network/arch-sdk 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@arch-network/arch-sdk 的下载量有多少?

根据 npm 官方下载统计,@arch-network/arch-sdk 在 2026/10/07 – 2026/11/05 这 30 天内被下载 5,919 次,日均约 197 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@arch-network/arch-sdk 还在维护吗?

最新版本 0.13.0 发布于 2026/11/02(5 天前);至今共发布 8 个版本,其中过去 12 个月发布了 8 个;首次发布于 2026/02/18。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。