Closed thelord1 closed 2 months ago
Hi there,
Please log the response of getSwapInstructions
see if the server is returning the swap data, if the swap response is correct and includes a serializedTx
then its probably something wrong with your swap parameters like, amount, fee, and etc...
I receive a serializedTx and the swap details, but the same code was working this morning. I haven't changed anything, and now I'm getting the following error:
Error during swap process: Transaction initiation failed: Transaction resulted in an error. Internal error.
Here are the details from getSwapInstructions: Swap instructions response: { "transaction": { "serializedTx": "AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAQABAzkf+E17EOemUTZ97+a++ix3ShJSGH3epWMKZ2bOO2oZ4BOYlT753wwa80LQ2kkdtAHrOvocdQhScD1LeAOpxwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIZDGZA2IZrEzEOVzerReRy314ldtthUVICSamHzsSg9AQICAAEMAgAAAASAZRkAAAAAAA==", "txType": "v0", "executionTime": 7.2942347430000085 }, "swapDetails": { "inputAmount": 0.01, "outputAmount": 340411.897648, "minimumOutputAmount": 306370.707884, "priceData": { "spotPrice": null, "effectivePrice": null, "priceImpactPercentage": 1 }, "feeInfo": { "swapFee": 499998, "platformFeeAmount": 0, "platformFeeFormatted": 0 } }, "tokenInfo": { "sourceToken": { "address": "So11111111111111111111111111111111111111112", "decimalPlaces": 9 }, "destinationToken": { "address": "EdUiCoiCeuSkfrrGpwvRwAsYiCEophvWCqW4jShPpump", "decimalPlaces": 6 } } }
Can you attach the code plz? Also try a different RPC and see if that solves the problem.
I am using an RPC from QuickNode and here is my code:
const fetch = require('node-fetch'); // Ensure node-fetch is installed const { Keypair, Connection, PublicKey } = require("@solana/web3.js"); const { SolanaSwap } = require("@solxtence/solana-swap"); const { getAccount, getMint } = require('@solana/spl-token');
// Configuration for API and Solana const API_KEY = ''; const BASE_URL = 'https://public-api.dextools.io/trial/v2/pool/solana'; const SOLANA_ENDPOINT = "https://hidden-delicate-sheet.solana-mainnet.quiknode.pro/cb92a1ea267d06337b987e0996a74947fb9f9258"; const SOLANA_RPC_ENDPOINT = "https://api.mainnet-beta.solana.com";
const privateKeyArray = ; const keypair = Keypair.fromSecretKey(Uint8Array.from(privateKeyArray));
// Initialize SolanaSwap const solanaSwap = new SolanaSwap(keypair, SOLANA_ENDPOINT); const connection = new Connection(SOLANA_RPC_ENDPOINT);
let lastToken = null;
// Function to fetch newly listed tokens async function fetchNewlyListedTokens() { const now = new Date(); const oneMinuteAgo = new Date(now.getTime() - 60 1000); // 60 seconds 1000 milliseconds
const queryParams = new URLSearchParams({ sort: 'creationTime', order: 'asc', from: oneMinuteAgo.toISOString(), to: now.toISOString(), page: 0, pageSize: 5 });
const endpoint = ${BASE_URL}?${queryParams.toString()}
;
try { const response = await fetch(endpoint, { method: 'GET', headers: { 'accept': 'application/json', 'X-API-KEY': API_KEY } });
if (!response.ok) {
throw new Error(`Failed to fetch data: ${response.status} ${response.statusText}`);
}
const data = await response.json();
if (data && data.data && Array.isArray(data.data.results) && data.data.results.length > 0) {
lastToken = data.data.results[data.data.results.length - 1];
console.log("Fetched new token:");
console.log(`Address: ${lastToken.address}`);
console.log(`Symbol: ${lastToken.symbol}`);
// Proceed to swap with the latest token
await swapTokenToSOL(lastToken.address, lastToken.symbol);
} else {
// Retry every 10 seconds if no new tokens are found
setTimeout(fetchNewlyListedTokens, 10000);
}
} catch (error) { console.error('Error fetching newly listed tokens:', error.message); // Retry every 10 seconds if there was an error setTimeout(fetchNewlyListedTokens, 10000); } }
// Function to fetch token balance from the wallet async function getTokenBalance(wallet, tokenMintAddress) { try { const walletPublicKey = new PublicKey(wallet.publicKey); const mintAddress = new PublicKey(tokenMintAddress);
const accounts = await connection.getTokenAccountsByOwner(walletPublicKey, {
mint: mintAddress,
});
if (accounts.value.length === 0) {
console.log('No token accounts found for the given mint address.');
return 0;
}
const tokenAccount = accounts.value[0].pubkey;
const accountInfo = await getAccount(connection, tokenAccount, 'confirmed');
const mintInfo = await getMint(connection, mintAddress, 'confirmed');
const balance = Number(accountInfo.amount) / Math.pow(10, mintInfo.decimals);
console.log(`Balance of token ${tokenMintAddress}: ${balance}`);
return balance;
} catch (error) { console.error('Error fetching token balance:', error.message); return 0; // Return 0 in case of an error } }
// Function to swap token to SOL and back // Function to swap token to SOL and back async function swapTokenToSOL(tokenAddress, tokenSymbol) { try { // Swap SOL to the new token console.log('Fetching swap instructions...'); const swapResponse = await solanaSwap.getSwapInstructions( "So11111111111111111111111111111111111111112", // SOL Address tokenAddress, 0.01, // Example amount to swap 10, // Slippage tolerance keypair.publicKey.toBase58(), 0.0005 // Priority fee );
// Log the response from getSwapInstructions
console.log('Swap instructions response:', swapResponse);
if (swapResponse && swapResponse.serializedTx) {
console.log('Serialized Transaction:', swapResponse.serializedTx);
const txid = await solanaSwap.performSwap(swapResponse, {
sendConfig: { skipPreflight: true },
maxConfirmationAttempts: 30,
confirmationTimeout: 500,
commitmentLevel: "processed",
});
console.log(`Successfully swapped SOL for ${tokenSymbol}. Transaction hash: ${txid}`);
console.log(`TX on Solscan: https://solscan.io/tx/${txid}`);
console.log('Waiting for 20 seconds...');
await new Promise(resolve => setTimeout(resolve, 20000));
const tokenBalance = await getTokenBalance(keypair, tokenAddress);
console.log(`Token Balance: ${tokenBalance}`);
if (tokenBalance > 0) {
// Swap back the new token to SOL
console.log('Fetching swap back instructions...');
const swapBackResponse = await solanaSwap.getSwapInstructions(
tokenAddress,
"So11111111111111111111111111111111111111112", // SOL Address
tokenBalance, // Swap the entire balance of the new token
10, // Slippage tolerance
keypair.publicKey.toBase58(),
0.0005 // Priority fee
);
// Log the response from getSwapInstructions for swap back
console.log('Swap back instructions response:', swapBackResponse);
if (swapBackResponse && swapBackResponse.serializedTx) {
console.log('Serialized Transaction for swap back:', swapBackResponse.serializedTx);
const swapBackTxid = await solanaSwap.performSwap(swapBackResponse, {
sendConfig: { skipPreflight: true },
maxConfirmationAttempts: 30,
confirmationTimeout: 500,
commitmentLevel: "processed",
});
console.log(`Successfully swapped ${tokenSymbol} back to SOL. Transaction hash: ${swapBackTxid}`);
console.log(`TX on Solscan: https://solscan.io/tx/${swapBackTxid}`);
} else {
console.log("No serialized transaction found for swap back.");
}
} else {
console.log("No tokens available to swap back.");
}
// Continue fetching new tokens
fetchNewlyListedTokens();
} else {
console.log("No serialized transaction found for initial swap.");
}
} catch (error) { console.error('Error during swap process:', error.message);
// Check if it's a SendTransactionError
if (error.name === 'SendTransactionError') {
try {
const logs = await error.getLogs();
console.error('Transaction logs:', logs);
} catch (logError) {
console.error('Error fetching transaction logs:', logError.message);
}
}
// Retry the swap process
setTimeout(() => swapTokenToSOL(tokenAddress, tokenSymbol), 10000);
} }
// Start the fetching process fetchNewlyListedTokens();
Find skipPreflight: true
and set it to false
.
Run the code and see what error it gives you or if it ever reaches that point.
I’m trying to make transactions using your API, but I encountered the following errors today:
Transaction initiation failed Transaction confirmation failed I’m unable to complete any swaps. Could you please let me know if this issue is on the server side or if I might be doing something wrong? Any assistance would be greatly appreciated.