用于发送、模拟和管理交易的方法。
sendTransaction
sendTransaction(tx: Transaction): TransactionMetadata | FailedTransactionMetadata
执行一笔交易。成功时返回 TransactionMetadata,失败时返回
FailedTransactionMetadata。可通过
instanceof FailedTransactionMetadata 判断返回的是哪一种。失败的结果提供 err()
用于获取错误信息,以及 meta() 用于获取其元数据(包括日志)。
import { FailedTransactionMetadata } from "litesvm";
const result = client.svm.sendTransaction(signedTx);
if (result instanceof FailedTransactionMetadata) {
// Check for errors
console.error("Transaction failed:", result.err());
console.error("Logs:", result.meta().logs());
} else {
// Access result properties (note: these are getter functions)
console.log("Signature:", result.signature());
console.log("Compute units:", result.computeUnitsConsumed());
console.log("Logs:", result.logs());
}
FailedTransactionMetadata 来自 litesvm 包,该包由
@solana/kit-plugin-litesvm 安装。请通过
npm install litesvm 将其添加到你自己的依赖中,以便导入使用。
err()、computeUnitsConsumed()、
logs() 和 signature() 等交易结果属性是 getter 函数,而不是普通属性。请务必
加括号调用。
simulateTransaction
simulateTransaction(tx: Transaction): SimulatedTransactionInfo | FailedTransactionMetadata
在不修改状态的情况下模拟交易。
import { FailedTransactionMetadata } from "litesvm";
const simResult = client.svm.simulateTransaction(signedTx);
if (simResult instanceof FailedTransactionMetadata) {
console.error("Simulation failed:", simResult.err());
console.error("Logs:", simResult.meta().logs());
} else {
// Use .meta() to get TransactionMetadata
const meta = simResult.meta();
console.log("Would use", meta.computeUnitsConsumed(), "compute units");
console.log("Logs:", meta.logs());
// Get post-execution account states
const postAccounts = simResult.postAccounts();
console.log("Post-state accounts:", postAccounts);
}
区块哈希管理
latestBlockhash
latestBlockhash(): Blockhash
获取当前区块哈希。
const blockhash = client.svm.latestBlockhash();
console.log("Blockhash:", blockhash);
getLatestBlockhash(通过 client.rpc)
获取包含有效期信息的区块哈希,用于手动构建交易。
请使用 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() 等程序插件时,
无需自行获取区块哈希——client.sendTransaction()(以及
指令链上的 .sendTransaction() 辅助方法)会为你处理。
expireBlockhash
推进到新的区块哈希。适用于测试区块哈希过期的场景。
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 transaction
const result = client.svm.sendTransaction(signedTx);
// Later, retrieve it by signature (base58 string)
// Note: getTransaction expects a base58-encoded signature string