Shred Delivery and Sender are now live! Get earliest access to raw Solana data and optimized transaction sending. Learn about Shred Delivery | Learn about Sender
Shred Delivery and Sender are now live! Get earliest access to raw Solana data and optimized transaction sending. Learn about Shred Delivery | Learn about Sender
使用 Helius 优先费用 API,通过账户密钥估算 Solana 优先费用。为交易前分析和批量操作提供快速费用估算。
识别账户
调用API
应用费用
import { ComputeBudgetProgram } from "@solana/web3.js";
// 1. Identify accounts involved in your transaction
const accountKeys = [
"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", // Token program
"YOUR_WALLET_ADDRESS", // Your wallet
"RECIPIENT_ADDRESS" // Recipient
];
// 2. Get priority fee estimate
const priorityFee = await getPriorityFeeEstimate(connection, accountKeys, "Medium");
// 3. Add to your transaction
const priorityFeeIx = ComputeBudgetProgram.setComputeUnitPrice({
microLamports: priorityFee
});
transaction.add(priorityFeeIx);
async function getPriorityFeeEstimate(connection, accountKeys, priorityLevel = "Medium") {
const response = await fetch(connection.rpcEndpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
jsonrpc: "2.0",
id: "1",
method: "getPriorityFeeEstimate",
params: [{
accountKeys: accountKeys,
options: {
priorityLevel: priorityLevel,
recommended: true
}
}]
})
});
const result = await response.json();
if (result.error) {
throw new Error(`Fee estimation failed: ${JSON.stringify(result.error)}`);
}
return result.result.priorityFeeEstimate;
}
展开以查看完整实现
const {
Connection,
PublicKey,
Transaction,
ComputeBudgetProgram
} = require("@solana/web3.js");
// Initialize connection
const connection = new Connection("https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY");
async function analyzeAccountPriorityFees() {
// Define accounts involved in your transaction
const accountKeys = [
"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", // Token program
"YOUR_WALLET_ADDRESS", // Your wallet
"TOKEN_ACCOUNT_ADDRESS", // Token account
"RECIPIENT_ADDRESS" // Recipient
];
try {
// Get estimates for different priority levels
const [lowFee, mediumFee, highFee, veryHighFee] = await Promise.all([
getPriorityFeeEstimate(connection, accountKeys, "Low"),
getPriorityFeeEstimate(connection, accountKeys, "Medium"),
getPriorityFeeEstimate(connection, accountKeys, "High"),
getPriorityFeeEstimate(connection, accountKeys, "VeryHigh")
]);
console.log("Priority Fee Estimates:");
console.log(`Low: ${lowFee} micro-lamports`);
console.log(`Medium: ${mediumFee} micro-lamports`);
console.log(`High: ${highFee} micro-lamports`);
console.log(`VeryHigh: ${veryHighFee} micro-lamports`);
// Get all levels at once for comparison
const allLevels = await getAllPriorityLevels(connection, accountKeys);
console.log("\nAll priority levels:", allLevels);
return {
low: lowFee,
medium: mediumFee,
high: highFee,
veryHigh: veryHighFee,
allLevels
};
} catch (error) {
console.error("Error getting priority fees:", error);
throw error;
}
}
// Helper function to get all priority levels
async function getAllPriorityLevels(connection, accountKeys) {
const response = await fetch(connection.rpcEndpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
jsonrpc: "2.0",
id: "1",
method: "getPriorityFeeEstimate",
params: [{
accountKeys: accountKeys,
options: {
includeAllPriorityFeeLevels: true
}
}]
})
});
const result = await response.json();
if (result.error) {
throw new Error(`Fee estimation failed: ${JSON.stringify(result.error)}`);
}
return result.result.priorityFeeLevels;
}
// Run the analysis
analyzeAccountPriorityFees();
// Popular program accounts
const programAccounts = [
"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", // Token program
"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL", // Associated token program
"M2mx93ekt1fmXSVkTrUL9xVFHkmME8HTUi5Cyc5aF7K" // Metaplex program
];
const programFees = await getPriorityFeeEstimate(connection, programAccounts, "Medium");
console.log(`Program account fees: ${programFees} micro-lamports`);
空槽评估
evaluateEmptySlotAsZero
选项对于基于账户的估算特别有用:async function compareEmptySlotHandling(accountKeys) {
const withEmptyAsZero = await fetch(connection.rpcEndpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
jsonrpc: "2.0",
id: "1",
method: "getPriorityFeeEstimate",
params: [{
accountKeys: accountKeys,
options: {
priorityLevel: "Medium",
evaluateEmptySlotAsZero: true // Default: true
}
}]
})
});
const withoutEmptyAsZero = await fetch(connection.rpcEndpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
jsonrpc: "2.0",
id: "1",
method: "getPriorityFeeEstimate",
params: [{
accountKeys: accountKeys,
options: {
priorityLevel: "Medium",
evaluateEmptySlotAsZero: false
}
}]
})
});
const result1 = await withEmptyAsZero.json();
const result2 = await withoutEmptyAsZero.json();
console.log(`With empty as zero: ${result1.result.priorityFeeEstimate}`);
console.log(`Without empty as zero: ${result2.result.priorityFeeEstimate}`);
}
true
(默认)时,没有交易的槽位被视为零费用而不是被排除。这为活动稀少的账户提供了更平衡的估算。包含详细信息
async function getDetailedFeeEstimate(connection, accountKeys) {
const response = await fetch(connection.rpcEndpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
jsonrpc: "2.0",
id: "1",
method: "getPriorityFeeEstimate",
params: [{
accountKeys: accountKeys,
options: {
includeDetails: true,
priorityLevel: "Medium"
}
}]
})
});
const result = await response.json();
console.log("Detailed fee analysis:", result.result);
return result.result;
}
自定义回溯期
async function getCustomLookbackEstimate(accountKeys, lookbackSlots = 50) {
const response = await fetch(connection.rpcEndpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
jsonrpc: "2.0",
id: "1",
method: "getPriorityFeeEstimate",
params: [{
accountKeys: accountKeys,
options: {
priorityLevel: "Medium",
lookbackSlots: lookbackSlots // 1-150, default is 150
}
}]
})
});
const result = await response.json();
return result.result.priorityFeeEstimate;
}
// Compare different lookback periods
const shortTerm = await getCustomLookbackEstimate(accountKeys, 50); // Recent trends
const longTerm = await getCustomLookbackEstimate(accountKeys, 150); // Historical average
console.log(`Short-term estimate: ${shortTerm} micro-lamports`);
console.log(`Long-term estimate: ${longTerm} micro-lamports`);
const writableAccounts = [
"YOUR_WALLET", // Paying fees
"TOKEN_ACCOUNT", // Being modified
"RECIPIENT_ACCOUNT" // Receiving tokens
];
const programAccounts = [
"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", // Token program
"CUSTOM_PROGRAM_ID" // Your program
];
class AccountBasedFeeEstimator {
constructor(connection) {
this.connection = connection;
this.fallbackFee = 10000; // 10k micro-lamports fallback
}
async getEstimate(accountKeys, priorityLevel = "Medium") {
try {
// Primary attempt
const estimate = await this.getPrimaryEstimate(accountKeys, priorityLevel);
return estimate;
} catch (error) {
console.warn("Primary estimate failed:", error.message);
// Fallback to different configuration
try {
return await this.getFallbackEstimate(accountKeys, priorityLevel);
} catch (fallbackError) {
console.warn("Fallback estimate failed:", fallbackError.message);
return this.fallbackFee;
}
}
}
async getPrimaryEstimate(accountKeys, priorityLevel) {
const response = await fetch(this.connection.rpcEndpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
jsonrpc: "2.0",
id: "1",
method: "getPriorityFeeEstimate",
params: [{
accountKeys: accountKeys,
options: {
priorityLevel: priorityLevel,
recommended: true
}
}]
})
});
const result = await response.json();
if (result.error) {
throw new Error(result.error.message);
}
return result.result.priorityFeeEstimate;
}
async getFallbackEstimate(accountKeys, priorityLevel) {
// Try with fewer accounts or different settings
const coreAccounts = accountKeys.slice(0, 3); // Take first 3 accounts
const response = await fetch(this.connection.rpcEndpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
jsonrpc: "2.0",
id: "1",
method: "getPriorityFeeEstimate",
params: [{
accountKeys: coreAccounts,
options: {
priorityLevel: "Medium", // Use medium as fallback
evaluateEmptySlotAsZero: true
}
}]
})
});
const result = await response.json();
if (result.error) {
throw new Error(result.error.message);
}
return result.result.priorityFeeEstimate;
}
}
// Usage
const estimator = new AccountBasedFeeEstimator(connection);
const fee = await estimator.getEstimate(accountKeys, "High");