solana-kit
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSolana Kit Development Guide
Solana Kit 开发指南
A comprehensive guide for building Solana applications with - the modern, tree-shakeable, zero-dependency JavaScript SDK from Anza.
@solana/kit本文是使用 构建Solana应用的综合指南——这是Anza推出的一款现代化、支持摇树优化、零依赖的JavaScript SDK。
@solana/kitOverview
概述
Solana Kit (formerly web3.js 2.0) is a complete rewrite of the Solana JavaScript SDK with:
- Tree-shakeable: Only ship code you use (-78% bundle size)
- Zero dependencies: No third-party packages
- Functional design: Composable, no classes
- 10x faster crypto: Native Ed25519 support
- TypeScript-first: Full type safety
Solana Kit(前身为web3.js 2.0)是Solana JavaScript SDK的完全重写版本,具备以下特性:
- 支持摇树优化:仅打包你实际使用的代码(包体积减少78%)
- 零依赖:无第三方依赖包
- 函数式设计:可组合,无类结构
- 加密操作快10倍:原生支持Ed25519
- 优先支持TypeScript:完整的类型安全
Quick Start
快速开始
Installation
安装
bash
npm install @solana/kitFor specific program interactions:
bash
npm install @solana-program/system @solana-program/tokenbash
npm install @solana/kit如需与特定程序交互:
bash
npm install @solana-program/system @solana-program/tokenMinimal Example
最简示例
typescript
import {
createSolanaRpc,
createSolanaRpcSubscriptions,
generateKeyPairSigner,
lamports,
pipe,
createTransactionMessage,
setTransactionMessageFeePayer,
setTransactionMessageLifetimeUsingBlockhash,
appendTransactionMessageInstruction,
signTransactionMessageWithSigners,
sendAndConfirmTransactionFactory,
getSignatureFromTransaction,
} from "@solana/kit";
import { getTransferSolInstruction } from "@solana-program/system";
const LAMPORTS_PER_SOL = BigInt(1_000_000_000);
async function transferSol() {
// 1. Connect to RPC
const rpc = createSolanaRpc("https://api.devnet.solana.com");
const rpcSubscriptions = createSolanaRpcSubscriptions("wss://api.devnet.solana.com");
// 2. Create signers
const sender = await generateKeyPairSigner();
const recipient = await generateKeyPairSigner();
// 3. Get blockhash
const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
// 4. Build transaction with pipe
const transactionMessage = pipe(
createTransactionMessage({ version: 0 }),
(tx) => setTransactionMessageFeePayer(sender.address, tx),
(tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),
(tx) => appendTransactionMessageInstruction(
getTransferSolInstruction({
amount: lamports(LAMPORTS_PER_SOL / BigInt(10)), // 0.1 SOL
destination: recipient.address,
source: sender,
}),
tx
)
);
// 5. Sign
const signedTx = await signTransactionMessageWithSigners(transactionMessage);
// 6. Send and confirm
const sendAndConfirm = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions });
await sendAndConfirm(signedTx, { commitment: "confirmed" });
console.log("Signature:", getSignatureFromTransaction(signedTx));
}typescript
import {
createSolanaRpc,
createSolanaRpcSubscriptions,
generateKeyPairSigner,
lamports,
pipe,
createTransactionMessage,
setTransactionMessageFeePayer,
setTransactionMessageLifetimeUsingBlockhash,
appendTransactionMessageInstruction,
signTransactionMessageWithSigners,
sendAndConfirmTransactionFactory,
getSignatureFromTransaction,
} from "@solana/kit";
import { getTransferSolInstruction } from "@solana-program/system";
const LAMPORTS_PER_SOL = BigInt(1_000_000_000);
async function transferSol() {
// 1. 连接到RPC
const rpc = createSolanaRpc("https://api.devnet.solana.com");
const rpcSubscriptions = createSolanaRpcSubscriptions("wss://api.devnet.solana.com");
// 2. 创建签名器
const sender = await generateKeyPairSigner();
const recipient = await generateKeyPairSigner();
// 3. 获取区块哈希
const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
// 4. 使用pipe构建交易
const transactionMessage = pipe(
createTransactionMessage({ version: 0 }),
(tx) => setTransactionMessageFeePayer(sender.address, tx),
(tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),
(tx) => appendTransactionMessageInstruction(
getTransferSolInstruction({
amount: lamports(LAMPORTS_PER_SOL / BigInt(10)), // 0.1 SOL
destination: recipient.address,
source: sender,
}),
tx
)
);
// 5. 签名交易
const signedTx = await signTransactionMessageWithSigners(transactionMessage);
// 6. 发送并确认交易
const sendAndConfirm = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions });
await sendAndConfirm(signedTx, { commitment: "confirmed" });
console.log("交易签名:", getSignatureFromTransaction(signedTx));
}Core Concepts
核心概念
1. RPC Connections
1. RPC连接
Kit separates HTTP and WebSocket connections:
typescript
import { createSolanaRpc, createSolanaRpcSubscriptions } from "@solana/kit";
// HTTP for requests
const rpc = createSolanaRpc("https://api.devnet.solana.com");
// WebSocket for subscriptions
const rpcSubscriptions = createSolanaRpcSubscriptions("wss://api.devnet.solana.com");
// Make RPC calls
const slot = await rpc.getSlot().send();
const balance = await rpc.getBalance(address).send();
const { value: blockhash } = await rpc.getLatestBlockhash().send();Kit将HTTP和WebSocket连接分离:
typescript
import { createSolanaRpc, createSolanaRpcSubscriptions } from "@solana/kit";
// HTTP用于普通请求
const rpc = createSolanaRpc("https://api.devnet.solana.com");
// WebSocket用于订阅
const rpcSubscriptions = createSolanaRpcSubscriptions("wss://api.devnet.solana.com");
// 发起RPC调用
const slot = await rpc.getSlot().send();
const balance = await rpc.getBalance(address).send();
const { value: blockhash } = await rpc.getLatestBlockhash().send();2. Signers
2. 签名器
Kit uses signer interfaces instead of keypairs directly:
typescript
import {
generateKeyPairSigner,
createKeyPairSignerFromBytes,
address,
} from "@solana/kit";
// Generate new signer
const signer = await generateKeyPairSigner();
console.log("Address:", signer.address);
// From existing secret key (Uint8Array)
const existing = await createKeyPairSignerFromBytes(secretKeyBytes);
// Create address from string
const addr = address("11111111111111111111111111111111");Kit直接使用签名器接口而非密钥对:
typescript
import {
generateKeyPairSigner,
createKeyPairSignerFromBytes,
address,
} from "@solana/kit";
// 生成新的签名器
const signer = await generateKeyPairSigner();
console.log("地址:", signer.address);
// 从现有密钥(Uint8Array)创建签名器
const existing = await createKeyPairSignerFromBytes(secretKeyBytes);
// 从字符串创建地址
const addr = address("11111111111111111111111111111111");3. Transaction Building with Pipe
3. 使用Pipe构建交易
Kit uses functional composition via :
pipetypescript
import {
pipe,
createTransactionMessage,
setTransactionMessageFeePayer,
setTransactionMessageLifetimeUsingBlockhash,
appendTransactionMessageInstruction,
appendTransactionMessageInstructions,
prependTransactionMessageInstructions,
} from "@solana/kit";
const tx = pipe(
createTransactionMessage({ version: 0 }), // Create v0 message
(tx) => setTransactionMessageFeePayer(payer.address, tx), // Set fee payer
(tx) => setTransactionMessageLifetimeUsingBlockhash(blockhash, tx), // Set lifetime
(tx) => appendTransactionMessageInstruction(instruction1, tx), // Add instruction
(tx) => appendTransactionMessageInstructions([instruction2, instruction3], tx), // Add multiple
);Kit通过实现函数式组合:
pipetypescript
import {
pipe,
createTransactionMessage,
setTransactionMessageFeePayer,
setTransactionMessageLifetimeUsingBlockhash,
appendTransactionMessageInstruction,
appendTransactionMessageInstructions,
prependTransactionMessageInstructions,
} from "@solana/kit";
const tx = pipe(
createTransactionMessage({ version: 0 }), // 创建v0版本交易消息
(tx) => setTransactionMessageFeePayer(payer.address, tx), // 设置付费方
(tx) => setTransactionMessageLifetimeUsingBlockhash(blockhash, tx), // 设置交易有效期
(tx) => appendTransactionMessageInstruction(instruction1, tx), // 添加单个指令
(tx) => appendTransactionMessageInstructions([instruction2, instruction3], tx), // 添加多个指令
);4. Signing Transactions
4. 交易签名
typescript
import {
signTransactionMessageWithSigners,
partiallySignTransactionMessageWithSigners,
getSignatureFromTransaction,
} from "@solana/kit";
// Sign with all signers in the transaction
const signedTx = await signTransactionMessageWithSigners(transactionMessage);
// Partial signing (for multisig)
const partiallySignedTx = await partiallySignTransactionMessageWithSigners(
transactionMessage
);
// Get signature before sending
const signature = getSignatureFromTransaction(signedTx);typescript
import {
signTransactionMessageWithSigners,
partiallySignTransactionMessageWithSigners,
getSignatureFromTransaction,
} from "@solana/kit";
// 使用交易中的所有签名器完成签名
const signedTx = await signTransactionMessageWithSigners(transactionMessage);
// 部分签名(适用于多签场景)
const partiallySignedTx = await partiallySignTransactionMessageWithSigners(
transactionMessage
);
// 在发送前获取交易签名
const signature = getSignatureFromTransaction(signedTx);5. Sending Transactions
5. 发送交易
typescript
import {
sendAndConfirmTransactionFactory,
sendTransactionWithoutConfirmingFactory,
getBase64EncodedWireTransaction,
} from "@solana/kit";
// Send with confirmation (recommended)
const sendAndConfirm = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions });
await sendAndConfirm(signedTx, { commitment: "confirmed" });
// Send without waiting for confirmation
const send = sendTransactionWithoutConfirmingFactory({ rpc });
await send(signedTx, { commitment: "confirmed" });
// Manual encoding (low-level)
const encoded = getBase64EncodedWireTransaction(signedTx);
await rpc.sendTransaction(encoded, { encoding: "base64" }).send();typescript
import {
sendAndConfirmTransactionFactory,
sendTransactionWithoutConfirmingFactory,
getBase64EncodedWireTransaction,
} from "@solana/kit";
// 发送并等待确认(推荐方式)
const sendAndConfirm = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions });
await sendAndConfirm(signedTx, { commitment: "confirmed" });
// 发送但不等待确认
const send = sendTransactionWithoutConfirmingFactory({ rpc });
await send(signedTx, { commitment: "confirmed" });
// 手动编码(底层操作)
const encoded = getBase64EncodedWireTransaction(signedTx);
await rpc.sendTransaction(encoded, { encoding: "base64" }).send();6. Fetching Accounts
6. 查询账户
typescript
import {
fetchEncodedAccount,
fetchEncodedAccounts,
assertAccountExists,
} from "@solana/kit";
// Fetch single account
const account = await fetchEncodedAccount(rpc, address);
if (account.exists) {
console.log("Lamports:", account.lamports);
console.log("Owner:", account.programAddress);
console.log("Data:", account.data);
}
// Fetch multiple accounts
const accounts = await fetchEncodedAccounts(rpc, [addr1, addr2, addr3]);
// Assert account exists (throws if not)
assertAccountExists(account);typescript
import {
fetchEncodedAccount,
fetchEncodedAccounts,
assertAccountExists,
} from "@solana/kit";
// 查询单个账户
const account = await fetchEncodedAccount(rpc, address);
if (account.exists) {
console.log("Lamports数量:", account.lamports);
console.log("所属程序:", account.programAddress);
console.log("账户数据:", account.data);
}
// 查询多个账户
const accounts = await fetchEncodedAccounts(rpc, [addr1, addr2, addr3]);
// 断言账户存在(不存在则抛出错误)
assertAccountExists(account);Package Reference
包参考
Core Package
核心包
| Import | Description |
|---|---|
| Main package - includes everything below |
| 导入路径 | 描述 |
|---|---|
| 主包——包含以下所有功能 |
Individual Packages
独立子包
| Package | Purpose |
|---|---|
| RPC client creation |
| WebSocket subscriptions |
| Signing interfaces |
| Address utilities |
| Key generation |
| Transaction compilation |
| Message building |
| Account fetching |
| Data encoding/decoding |
| Error handling |
| 包名 | 用途 |
|---|---|
| RPC客户端创建 |
| WebSocket订阅 |
| 签名器接口 |
| 地址工具类 |
| 密钥生成 |
| 交易编译 |
| 交易消息构建 |
| 账户查询 |
| 数据编解码 |
| 错误处理 |
Program Packages
程序相关包
| Package | Program |
|---|---|
| System Program |
| SPL Token |
| Token Extensions |
| Memo Program |
| Compute Budget |
| Lookup Tables |
| 包名 | 对应程序 |
|---|---|
| 系统程序 |
| SPL代币程序 |
| 代币扩展程序 |
| 备注程序 |
| 计算预算程序 |
| 地址查找表程序 |
Common Patterns
常见模式
Pattern 1: Helper Function for Send & Confirm
模式1:发送并确认交易的工具函数
typescript
import {
signTransactionMessageWithSigners,
sendAndConfirmTransactionFactory,
getSignatureFromTransaction,
CompilableTransactionMessage,
TransactionMessageWithBlockhashLifetime,
Commitment,
} from "@solana/kit";
function createTransactionSender(rpc: Rpc, rpcSubscriptions: RpcSubscriptions) {
const sendAndConfirm = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions });
return async (
txMessage: CompilableTransactionMessage & TransactionMessageWithBlockhashLifetime,
commitment: Commitment = "confirmed"
) => {
const signedTx = await signTransactionMessageWithSigners(txMessage);
await sendAndConfirm(signedTx, { commitment, skipPreflight: false });
return getSignatureFromTransaction(signedTx);
};
}
// Usage
const sendTx = createTransactionSender(rpc, rpcSubscriptions);
const signature = await sendTx(transactionMessage);typescript
import {
signTransactionMessageWithSigners,
sendAndConfirmTransactionFactory,
getSignatureFromTransaction,
CompilableTransactionMessage,
TransactionMessageWithBlockhashLifetime,
Commitment,
} from "@solana/kit";
function createTransactionSender(rpc: Rpc, rpcSubscriptions: RpcSubscriptions) {
const sendAndConfirm = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions });
return async (
txMessage: CompilableTransactionMessage & TransactionMessageWithBlockhashLifetime,
commitment: Commitment = "confirmed"
) => {
const signedTx = await signTransactionMessageWithSigners(txMessage);
await sendAndConfirm(signedTx, { commitment, skipPreflight: false });
return getSignatureFromTransaction(signedTx);
};
}
// 使用示例
const sendTx = createTransactionSender(rpc, rpcSubscriptions);
const signature = await sendTx(transactionMessage);Pattern 2: Reusable Transaction Builder
模式2:可复用的交易构建器
typescript
import {
pipe,
createTransactionMessage,
setTransactionMessageFeePayer,
setTransactionMessageLifetimeUsingBlockhash,
appendTransactionMessageInstructions,
IInstruction,
} from "@solana/kit";
async function buildTransaction(
rpc: Rpc,
feePayer: Address,
instructions: IInstruction[]
) {
const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
return pipe(
createTransactionMessage({ version: 0 }),
(tx) => setTransactionMessageFeePayer(feePayer, tx),
(tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),
(tx) => appendTransactionMessageInstructions(instructions, tx)
);
}typescript
import {
pipe,
createTransactionMessage,
setTransactionMessageFeePayer,
setTransactionMessageLifetimeUsingBlockhash,
appendTransactionMessageInstructions,
IInstruction,
} from "@solana/kit";
async function buildTransaction(
rpc: Rpc,
feePayer: Address,
instructions: IInstruction[]
) {
const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
return pipe(
createTransactionMessage({ version: 0 }),
(tx) => setTransactionMessageFeePayer(feePayer, tx),
(tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),
(tx) => appendTransactionMessageInstructions(instructions, tx)
);
}Pattern 3: Add Compute Budget
模式3:添加计算预算
typescript
import {
getSetComputeUnitLimitInstruction,
getSetComputeUnitPriceInstruction,
} from "@solana-program/compute-budget";
const computeInstructions = [
getSetComputeUnitLimitInstruction({ units: 200_000 }),
getSetComputeUnitPriceInstruction({ microLamports: 1000n }),
];
const tx = pipe(
createTransactionMessage({ version: 0 }),
(tx) => setTransactionMessageFeePayer(payer.address, tx),
(tx) => setTransactionMessageLifetimeUsingBlockhash(blockhash, tx),
(tx) => prependTransactionMessageInstructions(computeInstructions, tx), // Prepend!
(tx) => appendTransactionMessageInstruction(mainInstruction, tx),
);typescript
import {
getSetComputeUnitLimitInstruction,
getSetComputeUnitPriceInstruction,
} from "@solana-program/compute-budget";
const computeInstructions = [
getSetComputeUnitLimitInstruction({ units: 200_000 }),
getSetComputeUnitPriceInstruction({ microLamports: 1000n }),
];
const tx = pipe(
createTransactionMessage({ version: 0 }),
(tx) => setTransactionMessageFeePayer(payer.address, tx),
(tx) => setTransactionMessageLifetimeUsingBlockhash(blockhash, tx),
(tx) => prependTransactionMessageInstructions(computeInstructions, tx), // 要放在前面!
(tx) => appendTransactionMessageInstruction(mainInstruction, tx),
);Pattern 4: Versioned Transactions with Lookup Tables
模式4:使用查找表的版本化交易
typescript
import {
setTransactionMessageAddressLookupTable,
} from "@solana/kit";
// Fetch lookup table
const lookupTableAccount = await fetchAddressLookupTable(rpc, lookupTableAddress);
const tx = pipe(
createTransactionMessage({ version: 0 }),
(tx) => setTransactionMessageFeePayer(payer.address, tx),
(tx) => setTransactionMessageLifetimeUsingBlockhash(blockhash, tx),
(tx) => setTransactionMessageAddressLookupTable(tx, lookupTableAccount),
(tx) => appendTransactionMessageInstructions(instructions, tx),
);typescript
import {
setTransactionMessageAddressLookupTable,
} from "@solana/kit";
// 查询查找表
const lookupTableAccount = await fetchAddressLookupTable(rpc, lookupTableAddress);
const tx = pipe(
createTransactionMessage({ version: 0 }),
(tx) => setTransactionMessageFeePayer(payer.address, tx),
(tx) => setTransactionMessageLifetimeUsingBlockhash(blockhash, tx),
(tx) => setTransactionMessageAddressLookupTable(tx, lookupTableAccount),
(tx) => appendTransactionMessageInstructions(instructions, tx),
);Type Safety
类型安全
Kit provides comprehensive TypeScript types:
typescript
import type {
Address,
Signature,
Lamports,
TransactionMessage,
Rpc,
RpcSubscriptions,
KeyPairSigner,
} from "@solana/kit";
// Addresses are branded strings
const addr: Address = address("11111111111111111111111111111111");
// Lamports are branded bigints
const amount: Lamports = lamports(1_000_000_000n);
// Type-safe RPC responses
const response = await rpc.getBalance(addr).send();
// response.value is typed as LamportsKit提供全面的TypeScript类型支持:
typescript
import type {
Address,
Signature,
Lamports,
TransactionMessage,
Rpc,
RpcSubscriptions,
KeyPairSigner,
} from "@solana/kit";
// 地址为带标识的字符串类型
const addr: Address = address("11111111111111111111111111111111");
// Lamports为带标识的bigint类型
const amount: Lamports = lamports(1_000_000_000n);
// 类型安全的RPC响应
const response = await rpc.getBalance(addr).send();
// response.value的类型为LamportsPerformance Tips
性能优化技巧
-
Import only what you need - Kit is tree-shakeabletypescript
// Good - only imports what's used import { createSolanaRpc, generateKeyPairSigner } from "@solana/kit"; // Also good - use subpackages for smaller bundles import { createSolanaRpc } from "@solana/rpc"; import { generateKeyPairSigner } from "@solana/signers"; -
Reuse RPC connections - Don't create per requesttypescript
// Create once const rpc = createSolanaRpc(endpoint); // Reuse everywhere await rpc.getBalance(addr1).send(); await rpc.getBalance(addr2).send(); -
Batch requests when possibletypescript
// Fetch multiple accounts in one request const accounts = await fetchEncodedAccounts(rpc, [addr1, addr2, addr3]); -
Use skipPreflight carefully - Faster but no simulationtypescript
await sendAndConfirm(tx, { commitment: "confirmed", skipPreflight: true });
-
仅导入需要的内容——Kit支持摇树优化typescript
// 推荐:仅导入使用的功能 import { createSolanaRpc, generateKeyPairSigner } from "@solana/kit"; // 同样推荐:使用子包进一步减小体积 import { createSolanaRpc } from "@solana/rpc"; import { generateKeyPairSigner } from "@solana/signers"; -
复用RPC连接——不要每次请求都创建新连接typescript
// 只创建一次 const rpc = createSolanaRpc(endpoint); // 全局复用 await rpc.getBalance(addr1).send(); await rpc.getBalance(addr2).send(); -
尽可能批量请求typescript
// 一次请求查询多个账户 const accounts = await fetchEncodedAccounts(rpc, [addr1, addr2, addr3]); -
谨慎使用skipPreflight——速度更快但无模拟验证typescript
await sendAndConfirm(tx, { commitment: "confirmed", skipPreflight: true });
Error Handling
错误处理
typescript
import { isSolanaError, SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS } from "@solana/errors";
try {
await sendAndConfirm(signedTx, { commitment: "confirmed" });
} catch (error) {
if (isSolanaError(error, SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS)) {
console.error("Not enough SOL for transaction");
} else if (isSolanaError(error)) {
console.error("Solana error:", error.context);
} else {
throw error;
}
}typescript
import { isSolanaError, SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS } from "@solana/errors";
try {
await sendAndConfirm(signedTx, { commitment: "confirmed" });
} catch (error) {
if (isSolanaError(error, SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS)) {
console.error("账户SOL余额不足,无法完成交易");
} else if (isSolanaError(error)) {
console.error("Solana错误:", error.context);
} else {
throw error;
}
}Migration from web3.js 1.x
从web3.js 1.x迁移
See the separate migration skill or use for interoperability:
@solana/compattypescript
import {
fromLegacyPublicKey,
fromLegacyKeypair,
fromVersionedTransaction,
fromLegacyTransactionInstruction,
} from "@solana/compat";
// Convert legacy PublicKey to Kit Address
const address = fromLegacyPublicKey(legacyPublicKey);
// Convert legacy Keypair to Kit CryptoKeyPair (async)
const keyPair = await fromLegacyKeypair(legacyKeypair);
// Convert legacy VersionedTransaction to Kit Transaction
const kitTransaction = fromVersionedTransaction(legacyVersionedTx);
// Convert legacy TransactionInstruction to Kit Instruction
const kitInstruction = fromLegacyTransactionInstruction(legacyInstruction);Note: The compat package converts FROM legacy TO Kit types. For reverse conversion, you may need to manually construct legacy objects.
可参考单独的迁移指南,或使用包实现兼容:
@solana/compattypescript
import {
fromLegacyPublicKey,
fromLegacyKeypair,
fromVersionedTransaction,
fromLegacyTransactionInstruction,
} from "@solana/compat";
// 将旧版PublicKey转换为Kit的Address类型
const address = fromLegacyPublicKey(legacyPublicKey);
// 将旧版Keypair转换为Kit的CryptoKeyPair类型(异步操作)
const keyPair = await fromLegacyKeypair(legacyKeypair);
// 将旧版VersionedTransaction转换为Kit的Transaction类型
const kitTransaction = fromVersionedTransaction(legacyVersionedTx);
// 将旧版TransactionInstruction转换为Kit的Instruction类型
const kitInstruction = fromLegacyTransactionInstruction(legacyInstruction);注意:兼容包仅支持从旧版类型转换为Kit类型。如需反向转换,可能需要手动构建旧版对象。
Performance Benchmarks
性能基准测试
Kit delivers significant performance improvements over web3.js 1.x:
| Metric | web3.js 1.x | @solana/kit | Improvement |
|---|---|---|---|
| Keypair Generation | ~50ms | ~5ms | 10x faster |
| Transaction Signing | ~20ms | ~2ms | 10x faster |
| Bundle Size | 311KB | 226KB | 26% smaller |
| Confirmation Latency | ~400ms | ~200ms | ~200ms faster |
Benchmarks from Triton One's Ping Thing service and Solana Explorer testing
Kit相比web3.js 1.x有显著的性能提升:
| 指标 | web3.js 1.x | @solana/kit | 提升幅度 |
|---|---|---|---|
| 密钥对生成 | ~50ms | ~5ms | 快10倍 |
| 交易签名 | ~20ms | ~2ms | 快10倍 |
| 包体积 | 311KB | 226KB | 减小26% |
| 确认延迟 | ~400ms | ~200ms | 快约200ms |
测试数据来自Triton One的Ping Thing服务和Solana Explorer测试
Why It's Faster
性能提升原因
- Native Ed25519: Uses browser/runtime native crypto APIs
- Zero Dependencies: No third-party library overhead
- Tree-Shakeable: Only imports code you use
- No Classes: Functional design enables better optimization
- 原生Ed25519支持:使用浏览器/运行时原生加密API
- 零依赖:无第三方库带来的开销
- 支持摇树优化:仅打包实际使用的代码
- 无类结构:函数式设计可实现更优的编译优化
Resources
相关资源
Skill Structure
指南结构
solana-kit/
├── SKILL.md # This file
├── resources/
│ ├── packages-reference.md # Complete package documentation
│ └── api-quick-reference.md # Quick lookup table
├── examples/
│ ├── transfer-sol/ # Basic SOL transfer
│ ├── create-token/ # SPL token creation
│ ├── fetch-accounts/ # Account fetching & decoding
│ └── subscriptions/ # Real-time subscriptions
├── templates/
│ └── project-template.ts # Copy-paste starter
└── docs/
├── advanced-patterns.md # Complex patterns
└── troubleshooting.md # Common issuessolana-kit/
├── SKILL.md # 本文档
├── resources/
│ ├── packages-reference.md # 完整包文档
│ └── api-quick-reference.md # API速查表
├── examples/
│ ├── transfer-sol/ # 基础SOL转账示例
│ ├── create-token/ # SPL代币创建示例
│ ├── fetch-accounts/ # 账户查询与解码示例
│ └── subscriptions/ # 实时订阅示例
├── templates/
│ └── project-template.ts # 可直接复用的项目模板
└── docs/
├── advanced-patterns.md # 复杂使用模式
└── troubleshooting.md # 常见问题排查