Automated SOL Token Purchase Script
This script allows you to automatically purchase tokens on Solana using Jupiter's Swap API. It will ask for your wallet's private key and the token address you want to buy, then execute the transaction with optimized settings.
const { Connection, Keypair, VersionedTransaction } = require('@solana/web3.js');
const bs58 = require('bs58');
const fetch = require('cross-fetch');
const readline = require('readline');
// Create readline interface for user input
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Connect to Solana network with a reliable RPC
const connection = new Connection('https://neat-hidden-sanctuary.solana-mainnet.discover.quiknode.pro/2af5315d336f9ae920028bbb90a73b724dc1bbed/');
const SOL_MINT = 'So11111111111111111111111111111111111111112';
const SOL_AMOUNT = 100000; // 0.0001 SOL in lamports
async function main() {
try {
// Ask for user's private key
const privateKeyBase58 = await new Promise(resolve => {
rl.question('Enter your wallet private key (base58 encoded): ', answer => {
resolve(answer.trim());
});
});
// Ask for output token mint address
const outputMint = await new Promise(resolve => {
rl.question('Enter the token mint address you want to buy: ', answer => {
resolve(answer.trim());
});
});
// Create wallet from private key
const wallet = Keypair.fromSecretKey(bs58.decode(privateKeyBase58));
console.log(`Using wallet: ${wallet.publicKey.toString()}`);
console.log(`Buying 0.0001 SOL worth of token: ${outputMint}`);
// Execute the swap with retry logic
await executeSwapWithRetry(wallet, outputMint);
rl.close();
} catch (error) {
console.error('Error in main function:', error);
rl.close();
}
}
async function executeSwapWithRetry(wallet, outputMint, maxRetries = 5) {
let attempt = 0;
while (attempt < maxRetries) {
attempt++;
console.log(`Attempt ${attempt} of ${maxRetries}...`);
try {
// 1. Get quote
console.log('Getting quote...');
const quoteResponse = await (
await fetch(`https://quote-api.jup.ag/v6/quote?inputMint=${SOL_MINT}&outputMint=${outputMint}&amount=${SOL_AMOUNT}&slippageBps=50&restrictIntermediateTokens=true`)
).json();
if (quoteResponse.error) {
console.error('Error getting quote:', quoteResponse.error);
continue;
}
console.log(`Quote received. Expected output: ${quoteResponse.outAmount} ${outputMint}`);
// 2. Get serialized transaction
console.log('Preparing transaction...');
const { swapTransaction } = await (
await fetch('https://quote-api.jup.ag/v6/swap', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
quoteResponse,
userPublicKey: wallet.publicKey.toString(),
wrapAndUnwrapSol: true,
dynamicComputeUnitLimit: true,
dynamicSlippage: {
maxBps: 300 // 3% max slippage
},
prioritizationFeeLamports: {
priorityLevelWithMaxLamports: {
maxLamports: 10000000,
priorityLevel: "veryHigh"
}
}
})
})
).json();
// 3. Deserialize and sign transaction
console.log('Signing transaction...');
const swapTransactionBuf = Buffer.from(swapTransaction, 'base64');
const transaction = VersionedTransaction.deserialize(swapTransactionBuf);
transaction.sign([wallet]);
// 4. Execute the transaction
console.log('Executing transaction...');
const rawTransaction = transaction.serialize();
const txid = await connection.sendRawTransaction(rawTransaction, {
skipPreflight: true,
maxRetries: 2
});
console.log(`Transaction sent: https://solscan.io/tx/${txid}`);
// 5. Confirm transaction
console.log('Waiting for confirmation...');
const confirmation = await connection.confirmTransaction(txid);
if (confirmation.value.err) {
console.error('Transaction confirmed but has errors:', confirmation.value.err);
continue;
}
console.log('🎉 Transaction successful!');
return txid;
} catch (error) {
console.error(`Error during attempt ${attempt}:`, error.message);
console.log('Retrying...');
// Wait a bit before retrying
await new Promise(resolve => setTimeout(resolve, 2000));
}
}
throw new Error('Failed to execute swap after multiple attempts');
}
main().catch(err => {
console.error('Fatal error:', err);
process.exit(1);
});
How It Works
-
User Input: The script asks for your private key (base58 encoded) and the token mint address you want to purchase.
-
Connection Setup: Establishes a connection to the Solana network using a reliable RPC endpoint.
-
Quote Request: Requests a quote from Jupiter's API for buying 0.0001 SOL worth of your desired token with optimized settings:
- Uses
restrictIntermediateTokens=true to ensure stable routing through highly liquid tokens[8]
- Sets a default slippage of 50 bps (0.5%) for the initial quote[1]
-
Transaction Creation: Creates a swap transaction with optimized parameters:
- Uses
dynamicSlippage with a max cap of 300 bps (3%) for optimal success rate[8]
- Enables
dynamicComputeUnitLimit to optimize compute usage[6]
- Sets high priority fees through
prioritizationFeeLamports to ensure transactions land[8]
- Automatically wraps and unwraps SOL with
wrapAndUnwrapSol: true[1]
-
Transaction Execution: Signs and sends the transaction with retry logic:
- Uses
skipPreflight: true to avoid unnecessary simulation[6]
- Implements retry mechanism (up to 5 attempts)[4]
- Waits for confirmation before considering the transaction successful[1]
-
Result: Provides transaction URL so you can check the results on Solscan.
Requirements
Install the required dependencies before running:
npm install @solana/web3.js cross-fetch bs58 readline
Important Security Warning
NEVER share your private key. This script should only be run on a secure, private computer. Exposing your private key risks theft of your funds. Consider using a dedicated wallet with limited funds for testing purposes.