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 交易 IDvout: 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编号: 20000transports: ['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选择,以及与池或交易逻辑的集成.