在我的代码中使用 Node js 完成它
const executeSwap = async (quote, telegramId) => {
try {
logger.info('Starting executeSwap function');
const wallet = await getWallet(telegramId);
const connection = getConnection();
if (!wallet || !connection) {
throw new Error('Wallet or connection not initialized');
}
// Fetch the latest blockhash
logger.info('Fetching latest blockhash');
const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('finalized');
// Prepare swap request data
const swapRequestData = {
quoteResponse: quote,
userPublicKey: wallet.publicKey.toString(),
wrapUnwrapSOL: true,
computeUnitPriceMicroLamports: 3000000, // Adjust based on priority
computeUnitsLimit: 2368431, // Adjust based on priority
slippageBps: 50
};
const response = await axios.post(`${JUPITER_API_ENDPOINT}/swap`, swapRequestData);
const swapTransactionBuf = Buffer.from(response.data.swapTransaction, 'base64');
const transaction = VersionedTransaction.deserialize(swapTransactionBuf);
// Assign the latest blockhash
transaction.recentBlockhash = blockhash;
// Sign the transaction
transaction.sign([wallet]);
;
const rawTransaction = transaction.serialize();
const txid = await connection.sendRawTransaction(rawTransaction, {
skipPreflight: false,
preflightCommitment: 'finalized',
maxRetries: 3,
});
logger.info(`Transaction sent with ID: ${txid}`);
// Poll for confirmation
logger.info('Polling for transaction confirmation');
const confirmation = await pollTransactionConfirmation(connection, txid, 60 * 1000); // 60 seconds timeout
if (confirmation.value.err) {
logger.error(`Transaction failed: ${confirmation.value.err}`);
throw new Error(`Transaction failed: ${confirmation.value.err}`);
}
logger.info('Transaction confirmed successfully');
return {
success: true,
txid,
explorerUrl: `${SOLANA_EXPLORER}/${txid}`
};
} catch (error) {
logger.error(`Swap execution error: ${error.message}`);
if (error.message.includes('insufficient lamports') || error.message.includes('Insufficient SOL')) {
throw new Error('Insufficient SOL balance for transaction fees');
} else if (error.message.includes('block height exceeded') || error.message.includes('Signature')) {
throw new Error('Transaction signature expired. Please try again.');
}
throw error;
}
};
const pollTransactionConfirmation = async (connection, txid, timeout) => {
const startTime = Date.now();
const interval = 5000; // 2 seconds
while (Date.now() - startTime < timeout) {
const confirmation = await connection.confirmTransaction(txid, 'finalized');
if (confirmation.value || confirmation) {
return confirmation;
}
await new Promise(resolve => setTimeout(resolve, interval));
}
throw new Error('Transaction confirmation timeout');
};
我不断收到此错误
2024-11-25 11:40:46 [ERROR]: Swap execution error: Transaction was not confirmed in 60.00 seconds. It is unknown if it succeeded or failed. Check signature 4YkduMMzW4dYf3XqLpvGznqHfiKqGUznfSivEyRVJXByXgDNYS3crD7Gvrtryz1p1CjbVK51h8gMjUfmJaHRwucQ using the Solana Explorer or CLI tools.
2024-11-25 11:40:46 [ERROR]: Swap execution error: Transaction was not confirmed in 60.00 seconds. It is unknown if it succeeded or failed. Check signature 4YkduMMzW4dYf3XqLpvGznqHfiKqGUznfSivEyRVJXByXgDNYS3crD7Gvrtryz1p1CjbVK51h8gMjUfmJaHRwucQ using the Solana Explorer or CLI tools.
我不知道如何解决它并阻止它正确进行交换
我尝试了不同的方法
但不断给我这些错误,主要问题是我有很多超时错误,只有 10 个事务中的 1 个通过,其余的失败,其他方法也不起作用,我使用 Solana/web3.js、axios 和 Node js在 Telegram BOT 中
const { PublicKey, LAMPORTS_PER_SOL, VersionedTransaction, Connection } = require('@solana/web3.js');
const axios = require('axios');
const SOLANA_EXPLORER = 'https://solscan.io/tx';
const JUPITER_API_ENDPOINT = 'https://quote-api.jup.ag/v4/quote'; // Replace with actual Jupiter API endpoint
const executeSwap = async (quote, telegramId) => {
try {
logger.info('Starting executeSwap function');
const wallet = await getWallet(telegramId);
const connection = getConnection();
if (!wallet || !connection) {
throw new Error('Wallet or connection not initialized');
}
// Fetch the latest blockhash
logger.info('Fetching latest blockhash');
const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('finalized');
// Prepare swap request data
const swapRequestData = {
quoteResponse: quote,
userPublicKey: wallet.publicKey.toString(),
wrapUnwrapSOL: true,
computeUnitPriceMicroLamports: 3000000, // Adjust based on priority
computeUnitsLimit: 2368431, // Adjust based on priority
slippageBps: 50
};
logger.info('Requesting swap transaction from Jupiter API');
const response = await axios.post(`${JUPITER_API_ENDPOINT}/swap`, swapRequestData);
logger.info('Received swap transaction data from Jupiter');
const swapTransactionBuf = Buffer.from(response.data.swapTransaction, 'base64');
const transaction = VersionedTransaction.deserialize(swapTransactionBuf);
transaction.recentBlockhash = blockhash;
logger.info('Signing transaction');
transaction.sign([wallet]);
const rawTransaction = transaction.serialize();
logger.info('Sending raw transaction');
const txid = await connection.sendRawTransaction(rawTransaction, {
skipPreflight: false,
preflightCommitment: 'finalized',
maxRetries: 3,
});
logger.info(`Transaction sent with ID: ${txid}`);
// Poll for confirmation
const confirmation = await pollTransactionConfirmation(connection, txid, 60 * 1000); // 60 seconds timeout
if (confirmation.value.err) {
throw new Error(`Transaction failed: ${confirmation.value.err}`);
}
logger.info('Transaction confirmed successfully');
return {
success: true,
txid,
explorerUrl: `${SOLANA_EXPLORER}/${txid}`
};
} catch (error) {
logger.error(`Swap execution error: ${error.message}`);
if (error.message.includes('insufficient lamports') || error.message.includes('Insufficient SOL')) {
throw new Error('Insufficient SOL balance for transaction fees');
} else if (error.message.includes('block height exceeded') || error.message.includes('Signature')) {
throw new Error('Transaction signature expired. Please try again.');
}
throw error;
}
};
const pollTransactionConfirmation = async (connection, txid, timeout) => {
const startTime = Date.now();
const interval = 2000; // 2 seconds
while (Date.now() - startTime < timeout) {
const status = await connection.getSignatureStatus(txid, {
searchTransactionHistory: true,
});
if (status && status.value) {
return status;
}
await new Promise(resolve => setTimeout(resolve, interval));
}
throw new Error('Transaction confirmation timeout');
};
首先这不是 Jupiter API 问题。 Jupiter API 只是为您准备交易,它不会随后处理它。
我认为您在这个阶段有两个主要问题:您的 RPC 端点不够好,并且您在交易中没有使用优先费。如果您解决了这两个问题,您将在交易方面看到巨大的进步:
您还应该调整的事情,但请在下一步中考虑。
信息可能对您有用:
这是对基础知识的精彩而全面的解释。 如何分析频繁出现BlockHeightExceeded错误的原因?