用于发送、模拟和管理交易的方法。
sendTransaction
sendTransaction(tx: Transaction): TransactionMetadata | FailedTransactionMetadata
执行一笔交易。成功时返回元数据,失败时返回错误详情。
const result = client.svm.sendTransaction(signedTx);// Check for errorsif ("err" in result && result.err()) {console.error("Transaction failed:", result.err());return;}// Access result properties (note: these are getter functions)console.log("Signature:", result.signature());console.log("Compute units:", result.computeUnitsConsumed());console.log("Logs:", result.logs());
err()、computeUnitsConsumed()、
logs() 和 signature() 等交易结果属性是getter 函数,而非普通属性。调用时
请务必加上括号。
TransactionMetadata 方法
| 方法 | 返回值 | 描述 |
|---|---|---|
signature() | Uint8Array | 交易签名字节 |
computeUnitsConsumed() | bigint | 已消耗的计算单元 |
logs() | string[] | 程序日志 |
innerInstructions() | InnerInstruction[] | 内部(CPI)指令 |
returnData() | TransactionReturnData | 程序返回数据 |
prettyLogs() | string | 带颜色的格式化日志 |
simulateTransaction
simulateTransaction(tx: Transaction): SimulatedTransactionInfo | FailedTransactionMetadata
模拟一笔交易,不修改状态。
const simResult = client.svm.simulateTransaction(signedTx);if ("err" in simResult && simResult.err()) {console.error("Simulation failed:", simResult.err());return;}// Use .meta() to get TransactionMetadataconst meta = simResult.meta();console.log("Would use", meta.computeUnitsConsumed(), "compute units");console.log("Logs:", meta.logs());// Get post-execution account statesconst postAccounts = simResult.postAccounts();console.log("Post-state accounts:", postAccounts);
模拟不会改变状态。在发送交易前可使用模拟功能进行验证。
Blockhash 管理
latestBlockhash
latestBlockhash(): Blockhash
获取当前 blockhash。
const blockhash = client.svm.latestBlockhash();console.log("Blockhash:", blockhash);
getLatestBlockhash(通过 client.rpc)
获取带有生命周期信息的 blockhash,用于手动构建交易。
建议使用 RPC 辅助方法,因为它会同时返回 blockhash 和 lastValidBlockHeight。
import {createTransactionMessage,setTransactionMessageLifetimeUsingBlockhash} from "@solana/kit";const { value: blockhashLifetime } = await client.rpc.getLatestBlockhash().send();const tx = setTransactionMessageLifetimeUsingBlockhash(blockhashLifetime,createTransactionMessage({ version: 0 }));
当使用 systemProgram() 或 tokenProgram() 等程序插件时,
无需手动获取 blockhash——client.sendTransaction()(以及
指令链上的 .sendTransaction() 辅助方法)会自动为你处理。
expireBlockhash
expireBlockhash(): LiteSVM
切换到新的 blockhash。适用于测试 blockhash 过期场景。
const oldBlockhash = client.svm.latestBlockhash();client.svm.expireBlockhash();const newBlockhash = client.svm.latestBlockhash();console.log("Old:", oldBlockhash);console.log("New:", newBlockhash);// Blockhashes will be different
交易历史
启用交易历史记录以在发送后检索交易:
// Enable history storage (stores last N transactions)client.svm.withTransactionHistory(100n);// Send a transactionconst result = client.svm.sendTransaction(signedTx);// Later, retrieve it by signature (base58 string)// Note: getTransaction expects a base58-encoded signature string
Is this page helpful?