Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-search-preview-high-loc· OpenAIHugging Face LMArena Search Arena 24K

Simple script handling fully automated buy 0.0001SOL to ask user wallet private key…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Perplexitysonar-reasoning-pro-high’s answer.
  1. User

    Simple script handling fully automated buy 0.0001SOL to ask user wallet private key (format 54gfTrg456....) + address output mint token he want buy. When user have input address token, script build and perform automatically buy until successfully. Find documentation Jupiter Swap API on web. Lowest fee and autoslippage.

  2. Assistant

    To create a script that automates the purchase of 0.0001 SOL worth of a specified token using the Jupiter Swap API, follow these steps:

    1. Install Required Libraries: Ensure you have Node.js (version 16 or higher) installed. Then, install the necessary libraries:

      npm install @solana/web3.js cross-fetch @project-serum/anchor bs58
      
    2. Set Up the Script: Create a JavaScript file (e.g., buyToken.js) and include the following code:

      const { Connection, Keypair, VersionedTransaction } = require('@solana/web3.js');
      const fetch = require('cross-fetch');
      const { Wallet } = require('@project-serum/anchor');
      const bs58 = require('bs58');
      const readline = require('readline');
      
      // Initialize Solana connection
      const connection = new Connection('https://api.mainnet-beta.solana.com');
      
      // Function to prompt user input
      const prompt = (query) => {
        const rl = readline.createInterface({
          input: process.stdin,
          output: process.stdout,
        });
        return new Promise((resolve) => rl.question(query, (ans) => {
          rl.close();
          resolve(ans);
        }));
      };
      
      (async () => {
        try {
          // Prompt user for private key and token mint address
          const privateKeyInput = await prompt('Enter your wallet private key: ');
          const tokenMintAddress = await prompt('Enter the token mint address you want to buy: ');
      
          // Decode the private key and create a wallet
          const privateKey = bs58.decode(privateKeyInput);
          const wallet = new Wallet(Keypair.fromSecretKey(privateKey));
      
          // Define constants
          const SOL_MINT = 'So11111111111111111111111111111111111111112';
          const amount = 0.0001 * 10 ** 9; // 0.0001 SOL in lamports
          const slippageBps = 50; // 0.5% slippage
      
          // Function to fetch swap quote
          const getQuote = async () => {
            const response = await fetch(`https://api.jup.ag/swap/v6/quote?inputMint=${SOL_MINT}&outputMint=${tokenMintAddress}&amount=${amount}&slippageBps=${slippageBps}`);
            return response.json();
          };
      
          // Function to execute swap
          const executeSwap = async (quoteResponse) => {
            const swapResponse = await fetch('https://api.jup.ag/swap/v6/transaction', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({
                quoteResponse,
                userPublicKey: wallet.publicKey.toString(),
                wrapAndUnwrapSol: true,
              }),
            }).then((res) => res.json());
      
            const swapTransactionBuf = Buffer.from(swapResponse.swapTransaction, 'base64');
            const transaction = VersionedTransaction.deserialize(swapTransactionBuf);
            transaction.sign([wallet.payer]);
      
            const rawTransaction = transaction.serialize();
            const txid = await connection.sendRawTransaction(rawTransaction, {
              skipPreflight: true,
              maxRetries: 2,
            });
      
            await connection.confirmTransaction({
              blockhash: swapResponse.lastValidBlockHeight,
              lastValidBlockHeight: swapResponse.lastValidBlockHeight,
              signature: txid,
            });
      
            console.log(`Transaction successful: https://solscan.io/tx/${txid}`);
          };
      
          // Attempt to execute the swap until successful
          let success = false;
          while (!success) {
            try {
              const quoteResponse = await getQuote();
              await executeSwap(quoteResponse);
              success = true;
            } catch (error) {
              console.error('Swap failed, retrying...', error);
            }
          }
        } catch (error) {
          console.error('An error occurred:', error);
        }
      })();
      

    Explanation:

    • User Input: The script prompts the user to enter their wallet's private key and the mint address of the token they wish to purchase.

    • Wallet Setup: It decodes the provided private key to set up the user's wallet.

    • Swap Execution: The script fetches a swap quote from the Jupiter Swap API for 0.0001 SOL to the specified token, considering a slippage tolerance of 0.5%. It then constructs and signs the transaction, sending it to the Solana blockchain.

    • Retry Mechanism: If the swap fails (e.g., due to network issues or slippage), the script will retry until the transaction is successful.

    Security Note: Handling private keys directly in scripts poses significant security risks. Ensure that the environment where this script runs is secure, and avoid sharing or exposing your private key. For enhanced security, consider using secure key management solutions.

    References:

    • Jupiter Swap API Documentation[1]:

    • Payment API Guide[2]:

    • Self-hosted V6 Swap API[3]:

    By following this approach, you can automate the purchase of tokens on the Solana blockchain using the Jupiter Swap API, ensuring minimal fees and optimal slippage settings.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.