I try to swap USDT to other token through SWAP API but it got the same error.block height exceeded.
this is my swap function
async function handleSwap(wallet: any, coinName: string, amount: number) {
if (!wallet.connected || !wallet.signTransaction) {
toast.error("Please connect your wallet first", {
position: "bottom-center"
});
return;
}
const fromToken = "USDT";
const fromMint = TOKEN_MINTS[fromToken];
const toMint = TOKEN_MINTS[coinName];
if (!fromMint || !toMint) {
toast.error(`Unsupported token pair: ${fromToken} to ${coinName}`, {
position: "bottom-center"
});
return;
}
try {
const amountInDecimals = amount;
const quoteUrl = `https://quote-api.jup.ag/v6/quote?inputMint=${fromMint}&outputMint=${toMint}&amount=${amountInDecimals}&slippageBps=50`;
const quoteResponse = await fetch(quoteUrl).then((res) => res.json());
if (!quoteResponse || quoteResponse.error) {
throw new Error(quoteResponse.error || "Failed to get quote");
}
const swapRequestBody = {
quoteResponse,
userPublicKey: wallet.publicKey.toString(),
wrapAndUnwrapSol: true,
computeUnitPriceMicroLamports: 50000,
priorityLevelWithMaxLamports: {
priorityLevel: "high",
maxLamports: 100000
},
};
const { swapTransaction } = await fetch(
"https://quote-api.jup.ag/v6/swap",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(swapRequestBody)
}
).then((res) => res.json());
const swapTransactionBuf = Buffer.from(swapTransaction, "base64");
const transaction = VersionedTransaction.deserialize(swapTransactionBuf);
// Get latest blockhash before signing
const latestBlockhash = await connection.getLatestBlockhash("confirmed");
transaction.message.recentBlockhash = latestBlockhash.blockhash;
const signedTransaction = await wallet.signTransaction(transaction);
const rawTransaction = signedTransaction.serialize();
// Function to send transaction with retries
const sendTransactionWithRetry = async (
rawTx: Buffer,
maxRetries = 3,
retryDelay = 1000
): Promise<string> => {
let lastError;
for (let i = 0; i < maxRetries; i++) {
try {
const txid = await connection.sendRawTransaction(rawTx, {
skipPreflight: true,
maxRetries: 2,
preflightCommitment: "confirmed"
});
// Wait for confirmation with a timeout
const status = await Promise.race([
connection.confirmTransaction({
signature: txid,
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight
}),
new Promise((_, reject) =>
setTimeout(() => reject(new Error("Confirmation timeout")), 30000)
)
]);
if ((status as any).value.err) {
throw new Error("Transaction failed");
}
return txid;
} catch (error) {
lastError = error;
if (i < maxRetries - 1) {
await new Promise((resolve) => setTimeout(resolve, retryDelay));
// Get fresh blockhash for retry
const newBlockhash = await connection.getLatestBlockhash(
"confirmed"
);
transaction.message.recentBlockhash = newBlockhash.blockhash;
const newSignedTx = await wallet.signTransaction(transaction);
rawTx = newSignedTx.serialize();
}
}
}
throw lastError;
};
const txid = await sendTransactionWithRetry(rawTransaction);
console.log(`https://solscan.io/tx/${txid}`);
toast.success("Transaction confirmed!", {
position: "bottom-center"
});
} catch (error) {
console.error("Error signing or sending the transaction:", error);
toast.error(
`Transaction failed: ${
error instanceof Error ? error.message : "Unknown error"
}`,
{
position: "bottom-center"
}
);
}
}```