I have integrated Jupiter swap api on my react app and swapping tokens using Jupiter api but the swap is working sometimes and not working sometimes with TransactionExpiredBlockheightExceededError.
I was tried to raise prioritizationFeeLamports but not working well yet.
Here are my code.
const JUPITER_QUOTE_API = 'https://quote-api.jup.ag/v6/quote';
const JUPITER_SWAP_API = 'https://quote-api.jup.ag/v6/swap';
// Step 1: Fetch swap info from Jupiter
const fetchSwapInfo = async (inputMint: string, outputMint: string, amount: number) => {
const url = `${JUPITER_QUOTE_API}?inputMint=${inputMint}&outputMint=${outputMint}&amount=${amount}&slippageBps=150&&swapMode=ExactIn&onlyDirectRoutes=false&asLegacyTransaction=false&maxAccounts=64&minimizeSlippage=false`;
const response = await fetch(url);
const data = await response.json();
return {
inAmount: data.inAmount,
otherAmountThreshold: data.otherAmountThreshold,
quoteResponse: data,
};
};
// Step 2: Fetch swap transaction from Jupiter
const fetchSwapTransaction = async (
walletAddress: PublicKey | null,
recipientAddress: string,
swapInfo: any
) => {
if (!walletAddress || !recipientAddress || !swapInfo?.quoteResponse) {
throw new Error('Invalid parameters: Ensure walletAddress, recipientAddress, and swapInfo are defined.');
}
const requestBody = {
userPublicKey: walletAddress.toBase58(),
destinationTokenAccount: recipientAddress,
useSharedAccounts: true,
quoteResponse: swapInfo.quoteResponse,
allowOptimizedWrappedSolTokenAccount : true,
asLegacyTransaction : false,
dynamicComputeUnitLimit : true,
prioritizationFeeLamports:{
priorityLevelWithMaxLamports:{
global:false,
maxLamports: 4000000,
priorityLevel: "veryHigh"
}
},
wrapAndUnwrapSol: true,
};
const response = await fetch(JUPITER_SWAP_API, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(requestBody),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Error fetching swap transaction: ${errorText}`);
}
const { swapTransaction, lastValidBlockHeight } = await response.json();
return { swapTransaction, lastValidBlockHeight };
};
// Function to find the fee account and get serialized transactions for the swap
// Step 3: Send transaction to Solana blockchain
const sendTransaction = async (swapTransaction: string, walletAdapter: WalletAdapter) => {
let latestBlockHash = await connection.getLatestBlockhash();
// deserialize the transaction
const swapTransactionBuf = Buffer.from(swapTransaction, 'base64');
var transaction = VersionedTransaction.deserialize(swapTransactionBuf);
console.log(transaction);
// Set the recent blockhash
transaction.message.recentBlockhash = latestBlockHash.blockhash;
const signedTransaction = await (walletAdapter as any).signTransaction(transaction);
// Execute the transaction
const rawTransaction = transaction.serialize()
latestBlockHash = await connection.getLatestBlockhash();
const txid = await connection.sendRawTransaction(rawTransaction, {
skipPreflight: false,
maxRetries: 5,
});
// get the latest block hash
console.log(`https://solscan.io/tx/${txid}`);
setIsConfirming(true);
await connection.confirmTransaction({
blockhash: latestBlockHash.blockhash,
lastValidBlockHeight: latestBlockHash.lastValidBlockHeight,
signature: txid
});
setIsConfirming(false);
setTransactionLink(`https://solscan.io/tx/${txid}`);
console.log(`https://solscan.io/tx/${txid}`);
return txid;
};
// Step 4: Main function to swap and send token
const swapAndSendToken = async (
walletAdapter: WalletAdapter,
recipientAddress: string,
inputMint: string,
outputMint: string,
amount: number
) => {
try {
const walletPublicKey = walletAdapter.publicKey;
// Step 1: Fetch swap info
const swapInfo = await fetchSwapInfo(inputMint, outputMint, amount);
// Step 2: Fetch the swap transaction
const { swapTransaction, lastValidBlockHeight } = await fetchSwapTransaction(walletPublicKey, recipientAddress, swapInfo);
console.log(swapTransaction);
// Step 3: Send the transaction to the blockchain
let txid = await sendTransaction(swapTransaction, walletAdapter);
console.log('$ sent successfully!n https://solscan.io/tx/' + txid);
console.log('Swap and send transaction completed successfully.');
setIsSuccessful(true);
} catch (error) {
console.error('Error during swap and send:', error);
setIsBroken(true);
//alert("Failed! " + error.message);
}
};
const payCoin = async () => {
if(isProcessing) return;
setIsProcessing(true);
const inputToken = token;
var targetTokenName = data?.transactions?.currency;
if(inputToken.name == targetTokenName)
{
alert("direct token send, coming soon!")
}
else {
var targetUnitNumber = 0;
var targetMint = "";
Tokens.forEach((element) => {
if (element.name == targetTokenName) {
targetMint = element.mintAddress;
targetUnitNumber = element.decimals;
}
});
var merchant_address = data?.transactions?.merchant_address
//the public solana address
const accountPublicKey = new PublicKey(
merchant_address
);
//mintAccount = the token mint address
const mintAccount = new PublicKey(
targetMint
);
const account = await connection.getTokenAccountsByOwner(accountPublicKey, {
mint: mintAccount});
if(account.value.length==0) {
alert("can not find merchant account address for this spl token!");
}
else {
await swapAndSendToken(
walletAdapter,
account.value[0].pubkey.toString(), // Merchant's USDC address
inputToken.mintAddress, // Input mint address
targetMint, // Output mint address
tokenAmount * (10 ** inputToken.decimals) // Example: 0.1 USDC in micro-lamports
);
}
}
setIsProcessing(false);
}
In this code, I added prioritizationFeeLamports and tried to raise the fee to prevent failing transaction but it’s failing many times.
How to raise the fee amount for Jupiter transaction?