Jupiter API 中的超时错误

问题描述 投票:0回答:1

在我的代码中使用 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');
};
javascript node.js blockchain solana
1个回答
0
投票

首先这不是 Jupiter API 问题。 Jupiter API 只是为您准备交易,它不会随后处理它。

我认为您在这个阶段有两个主要问题:您的 RPC 端点不够好,并且您在交易中没有使用优先费。如果您解决了这两个问题,您将在交易方面看到巨大的进步:

  1. RPC 确实很重要。使用您自己的 RPC 或专用/共享 RPC 提供程序(Triton、Helius、Quiknode、Ankr)。
  2. 您应该尝试使用prioritizationFeeLamports 参数。如果没有优先费,您落地交易的机会接近于零。

您还应该调整的事情,但请在下一步中考虑。

  1. 在清楚地了解应该使用什么值之前,不要在交换请求参数中使用严格的值。 Jupiter 有很多不错且有用的自动化参数供您使用,让您以高概率完成交易:不要使用computeUnitPriceMicroLamports 参数并使用dynamicComputeUnitLimit=true 参数;不要使用严格的滑点值,并从具有 maxBps 值的dynamicSlippage 参数开始(或者甚至在交换请求中根本不使用。让 Jupiter 使用报价响应中的推荐值)。
  2. 您使用 sendRawTransaction 方法。您应该考虑到这不是完成交易的最佳方法。甚至 Jupiter 文档也说“由于 Solana 上的网络拥塞,sendRawTransaction 方法可能无法帮助您完成交易......”。

信息可能对您有用:

Jupiter 文档 - 登陆交易

这是对基础知识的精彩而全面的解释。 如何分析频繁出现BlockHeightExceeded错误的原因?

© www.soinside.com 2019 - 2024. All rights reserved.