dotenv.config();
const connection = new Connection('https://api.mainnet-beta.solana.com', 'confirmed');
const wallet = new Keypair(Uint8Array.from(JSON.parse(process.env.PRIVATE_KEY)));
async function fetchWithRetry(url, options, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.log(`Retry attempt ${i + 1} due to error:`, error.message);
await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
}
}
throw new Error('Max retries reached. Could not fetch data.');
}
async function executeTrade() {
try {
const SOL_MINT = 'So11111111111111111111111111111111111111112'; // SOL mint address
const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'; // USDC mint address
const solAmount = 0.025; // 0.05 SOL for $5 if SOL price is $100
const solInLamports = Math.floor(solAmount * 1e9); // Convert to lamports
// Buy USDC with SOL
const buyQuoteResponse = await fetchWithRetry(`https://quote- api.jup.ag/v6/quote? inputMint=${SOL_MINT}&outputMint=${USDC_MINT}&amount=${solInLamports}&slippageBps=50`);
const buyQuote = buyQuoteResponse;
console.log('Buy Quote:', JSON.stringify(buyQuote, null, 2));
if (buyQuote.error) throw new Error('Error fetching buy quote: ' + JSON.stringify(buyQuote.error));
const buySwapResponse = await fetchWithRetry('https://quote-api.jup.ag/v6/swap', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
quoteResponse: buyQuote,
userPublicKey: wallet.publicKey.toString(),
wrapAndUnwrapSol: true
})
});
const buySwap = buySwapResponse;
console.log('Buy Swap Response:', JSON.stringify(buySwap, null, 2));
if (buySwap.error) throw new Error('Error in buy swap: ' + JSON.stringify(buySwap.error));
// Enhanced error checking for swapTransaction
if (!buySwap.swapTransaction) {
console.log('Full Buy Swap Response:', JSON.stringify(buySwap, null, 2));
throw new Error('Buy swap transaction is not available in the response');
}
try {
// Check if the transaction can be deserialized as VersionedTransaction
let buyTransaction;
try {
buyTransaction = VersionedTransaction.deserialize(Buffer.from(buySwap.swapTransaction, 'base64'));
} catch (versionedError) {
// If VersionedTransaction fails, try with regular Transaction
console.log('Failed to deserialize as VersionedTransaction, trying as Transaction:', versionedError.message);
buyTransaction = Transaction.from(Buffer.from(buySwap.swapTransaction, 'base64'));
}
// Check if the transaction has the '_bn' property or similar
if (buyTransaction && buyTransaction._bn === undefined) {
console.log('Transaction does not have _bn property:', JSON.stringify(buyTransaction, null, 2));
throw new Error('Transaction object does not contain expected _bn property');
}
buyTransaction.sign([wallet]);
const buySignature = await connection.sendTransaction(buyTransaction, [wallet]);
await connection.confirmTransaction(buySignature);
console.log('USDC Buy Transaction confirmed:', `https://explorer.solana.com/tx/${buySignature}`);
} catch (deserializeError) {
console.error('Error in deserializing or signing buy transaction:', deserializeError.message);
throw deserializeError;
}
// Wait for 10 seconds
await new Promise(resolve => setTimeout(resolve, 10000));
// Convert USDC back to SOL
const usdcAmount = buyQuote.outAmount;
console.log('USDC Amount to sell:', usdcAmount);
if (usdcAmount === undefined) throw new Error('USDC amount to sell is undefined');
const sellQuoteResponse = await fetchWithRetry(`https://quote-api.jup.ag/v6/quote?inputMint=${USDC_MINT}&outputMint=${SOL_MINT}&amount=${usdcAmount}&slippageBps=50`);
const sellQuote = sellQuoteResponse;
console.log('Sell Quote:', JSON.stringify(sellQuote, null, 2));
if (sellQuote.error) throw new Error('Error fetching sell quote: ' + JSON.stringify(sellQuote.error));
const sellSwapResponse = await fetchWithRetry('https://quote-api.jup.ag/v6/swap', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
quoteResponse: sellQuote,
userPublicKey: wallet.publicKey.toString(),
wrapAndUnwrapSol: true
})
});
const sellSwap = sellSwapResponse;
console.log('Sell Swap Response:', JSON.stringify(sellSwap, null, 2));
if (sellSwap.error) throw new Error('Error in sell swap: ' + JSON.stringify(sellSwap.error));
// Enhanced error checking for swapTransaction
if (!sellSwap.swapTransaction) {
console.log('Full Sell Swap Response:', JSON.stringify(sellSwap, null, 2));
throw new Error('Sell swap transaction is not available in the response');
}
try {
// Check if the transaction can be deserialized as VersionedTransaction
let sellTransaction;
try {
sellTransaction = VersionedTransaction.deserialize(Buffer.from(sellSwap.swapTransaction, 'base64'));
} catch (versionedError) {
// If VersionedTransaction fails, try with regular Transaction
console.log('Failed to deserialize as VersionedTransaction, trying as Transaction:', versionedError.message);
sellTransaction = Transaction.from(Buffer.from(sellSwap.swapTransaction, 'base64'));
}
// Check if the transaction has the '_bn' property or similar
if (sellTransaction && sellTransaction._bn === undefined) {
console.log('Transaction does not have _bn property:', JSON.stringify(sellTransaction, null, 2));
throw new Error('Transaction object does not contain expected _bn property');
}
sellTransaction.sign([wallet]);
const sellSignature = await connection.sendTransaction(sellTransaction, [wallet]);
await connection.confirmTransaction(sellSignature);
console.log('SOL Sell Transaction confirmed:', `https://explorer.solana.com/tx/${sellSignature}`);
} catch (deserializeError) {
console.error('Error in deserializing or signing sell transaction:', deserializeError.message);
throw deserializeError;
}
console.log('Trade completed successfully.');
} catch (error) {
console.error('Error in trade execution:', error.message);
}
}
// Выполняем сделку
executeTrade().catch(console.error);
Я тестирую API-интерфейс свопа Jupiters v6 и пытаюсь совершить небольшую транзакцию, просто чтобы проверить, работает ли она, и я продолжаю получать эту ошибку: «Ошибка при выполнении сделки: невозможно прочитать свойства неопределенного (чтение '_bn')» не понимаю, почему это происходит, пожалуйста, кто-нибудь объясни.
console.log('Buy Swap Response:', JSON.stringify(buySwap, null, 2)); if (buySwap.error) throw new Error('Error in buy swap: ' + JSON.stringify(buySwap.error));
// Enhanced error checking for swapTransaction if (!buySwap.swapTransaction) { console.log('Full Buy Swap Response:', JSON.stringify(buySwap, null, 2)); throw new Error('Buy swap transaction is not available in the response'); }
try { // Check if the transaction can be deserialized as VersionedTransaction let buyTransaction; try { buyTransaction = VersionedTransaction.deserialize(Buffer.from(buySwap.swapTransaction, 'base64')); } catch (versionedError) { // If VersionedTransaction fails, try with regular Transaction console.log('Failed to deserialize as VersionedTransaction, trying as Transaction:', versionedError.message); buyTransaction = Transaction.from(Buffer.from(buySwap.swapTransaction, 'base64')); }
// Check if the transaction has the '_bn' property or similar if (buyTransaction && buyTransaction._bn === undefined) { console.log('Transaction does not have _bn property:', JSON.stringify(buyTransaction, null, 2)); throw new Error('Transaction object does not contain expected _bn property'); }
// Wait for 10 seconds await new Promise(resolve => setTimeout(resolve, 10000));
// Convert USDC back to SOL const usdcAmount = buyQuote.outAmount; console.log('USDC Amount to sell:', usdcAmount); if (usdcAmount === undefined) throw new Error('USDC amount to sell is undefined');
console.log('Sell Swap Response:', JSON.stringify(sellSwap, null, 2)); if (sellSwap.error) throw new Error('Error in sell swap: ' + JSON.stringify(sellSwap.error));
// Enhanced error checking for swapTransaction if (!sellSwap.swapTransaction) { console.log('Full Sell Swap Response:', JSON.stringify(sellSwap, null, 2)); throw new Error('Sell swap transaction is not available in the response'); }
try { // Check if the transaction can be deserialized as VersionedTransaction let sellTransaction; try { sellTransaction = VersionedTransaction.deserialize(Buffer.from(sellSwap.swapTransaction, 'base64')); } catch (versionedError) { // If VersionedTransaction fails, try with regular Transaction console.log('Failed to deserialize as VersionedTransaction, trying as Transaction:', versionedError.message); sellTransaction = Transaction.from(Buffer.from(sellSwap.swapTransaction, 'base64')); }
// Check if the transaction has the '_bn' property or similar if (sellTransaction && sellTransaction._bn === undefined) { console.log('Transaction does not have _bn property:', JSON.stringify(sellTransaction, null, 2)); throw new Error('Transaction object does not contain expected _bn property'); }
} catch (error) { console.error('Error in trade execution:', error.message); } [/code] } // Выполняем сделку executeTrade().catch(console.error); Я тестирую API-интерфейс свопа Jupiters v6 и пытаюсь совершить небольшую транзакцию, просто чтобы проверить, работает ли она, и я продолжаю получать эту ошибку: «Ошибка при выполнении сделки: невозможно прочитать свойства неопределенного (чтение '_bn')» не понимаю, почему это происходит, пожалуйста, кто-нибудь объясни.