https://dev.jup.ag/docs/swap-api/send-swap-transaction
- User
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, I can help you understand the purpose and content of the documentation page you linked: https://dev.jup.ag/docs/swap-api/send-swap-transaction.
Based on the provided URL (https://dev.jup.ag/docs/swap-api/send-swap-transaction) and the search results, here's a summary of what that documentation page covers:
Purpose:
The page focuses on the final steps of executing a token swap using the Jupiter Swap API on the Solana blockchain. It details how to take the swap transaction data, obtained from a previous API call (likely the /swap endpoint), and actually submit it to the Solana network.[1]
Key Steps Covered:
Prerequisites: It assumes you have already:
/quote API endpoint.[1][2][3]/swap API endpoint (or potentially /swap-instructions) to get the serialized transaction data based on that quote.[1][4][5]Preparing the Transaction:
/swap API endpoint is typically in a base64 encoded format.[6]VersionedTransaction in web3.js).[6]Signing the Transaction:
userPublicKey provided earlier). This proves ownership and authorizes the swap. The documentation likely provides code snippets showing how to sign the deserialized transaction object.Serializing the Signed Transaction:
Sending (Broadcasting) the Transaction:
sendTransaction from Solana's web3 libraries.[7]Optimizing Transaction Landing:
lastValidBlockHeight.[6][7]dynamicComputeUnitLimit).[8]Confirming the Transaction:
In essence, this page guides developers through the client-side (or backend) responsibilities of taking the transaction data provided by Jupiter's API, signing it securely, and reliably submitting it to the Solana blockchain for execution. It bridges the gap between getting the swap details from Jupiter and actually making the swap happen on-chain.
https://dev.jup.ag/docs/swap-api/build-swap-transaction https://dev.jup.ag/docs/swap-api/send-swap-transaction https://dev.jup.ag/docs/swap-api/get-quote . Script automatique achat de 0.0001 SOL vers SPL token solana par ligne de commande . Je veux que le script demande la clé privée et l'adresse du token . Ensuite le script effectue automatiquement la construction la signature et l'envoi automatique en utilisant toutes les url above 👆
Okay, let's craft a conceptual Python script to achieve this automated swap via the command line using the Jupiter API endpoints you provided.
Important Considerations & Disclaimers:
requests, solana, base58.
pip install requests solana base58
import requests
import base64
import base58
import time
import getpass # For securely getting the private key
from solders.keypair import Keypair # Use solders Keypair
from solders.pubkey import Pubkey
from solders.transaction import VersionedTransaction
from solders.hash import Hash # Import Hash
from solana.rpc.api import Client
from solana.rpc.types import TxOpts, Commitment
# --- Configuration ---
SOL_MINT_ADDRESS = "So11111111111111111111111111111111111111112" # SOL Mint address
AMOUNT_SOL = 0.0001 # Amount of SOL to swap
LAMPORTS_PER_SOL = 1_000_000_000
AMOUNT_LAMPORTS = int(AMOUNT_SOL * LAMPORTS_PER_SOL)
SLIPPAGE_BPS = 50 # 0.5% slippage tolerance (50 basis points)
PRIORITY_FEE_MICRO_LAMPORTS = 50000 # Example priority fee (adjust as needed)
# Use a reliable RPC endpoint
RPC_ENDPOINT = "https://api.mainnet-beta.solana.com" # Replace with your preferred RPC (Helius, QuickNode, Triton etc.)
# For Devnet, use: "https://api.devnet.solana.com"
# Jupiter API endpoints
QUOTE_URL = "https://quote-api.jup.ag/v6/quote"
SWAP_URL = "https://quote-api.jup.ag/v6/swap"
# --- Helper Functions ---
def get_jup_quote(input_mint, output_mint, amount_lamports, slippage_bps):
"""Fetches a swap quote from Jupiter API."""
print(f"1. Getting quote for {AMOUNT_SOL} SOL to {output_mint}...")
params = {
"inputMint": input_mint,
"outputMint": output_mint,
"amount": amount_lamports,
"slippageBps": slippage_bps,
# "onlyDirectRoutes": "false", # Optional: Allow multi-hop routes
# "asLegacyTransaction": "false" # Request Versioned Transaction
}
try:
response = requests.get(QUOTE_URL, params=params)
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
quote_data = response.json()
print(" Quote received.")
return quote_data
except requests.exceptions.RequestException as e:
print(f" Error fetching quote: {e}")
if response is not None:
print(f" Response status code: {response.status_code}")
print(f" Response text: {response.text}")
return None
except Exception as e:
print(f" An unexpected error occurred during quoting: {e}")
return None
def get_jup_swap_tx(quote_response, user_public_key_str, priority_fee_micro_lamports):
"""Fetches the swap transaction from Jupiter API."""
print("2. Getting swap transaction...")
payload = {
"quoteResponse": quote_response,
"userPublicKey": user_public_key_str,
"wrapAndUnwrapSol": True, # Automatically wrap/unwrap SOL
# "dynamicComputeUnitLimit": True, # Ask Jupiter to estimate compute limit
"prioritizationFeeLamports": priority_fee_micro_lamports # Use microLamports for v6
# "asLegacyTransaction": False # Request Versioned Transaction by default
}
try:
response = requests.post(SWAP_URL, json=payload)
response.raise_for_status()
swap_data = response.json()
print(" Swap transaction received.")
return swap_data.get("swapTransaction") # Base64 encoded transaction
except requests.exceptions.RequestException as e:
print(f" Error fetching swap transaction: {e}")
if response is not None:
print(f" Response status code: {response.status_code}")
print(f" Response text: {response.text}")
return None
except Exception as e:
print(f" An unexpected error occurred getting swap tx: {e}")
return None
def sign_and_send_transaction(encoded_tx, signer_keypair, rpc_client):
"""Deserializes, signs, and sends the transaction."""
print("3. Signing transaction...")
try:
# Decode the base64 transaction string
tx_bytes = base64.b64decode(encoded_tx)
# Deserialize the transaction
versioned_tx = VersionedTransaction.from_bytes(tx_bytes)
print(f" Transaction version: {versioned_tx.version}") # Log version (0=legacy, 1=versioned)
# Sign the transaction
signed_tx = signer_keypair.sign_message(versioned_tx.message.to_bytes())
versioned_tx.signatures[0] = signed_tx # Replace the placeholder signature
print("4. Sending transaction...")
# Send the transaction
opts = TxOpts(
skip_preflight=False, # Run preflight checks
preflight_commitment=Commitment("processed"), # Or "confirmed"/"finalized"
max_retries=5, # Add retries
)
send_result = rpc_client.send_transaction(versioned_tx, opts=opts)
tx_sig = send_result.value
print(f" Transaction sent successfully!")
print(f" Transaction signature: {tx_sig}")
return str(tx_sig) # Return signature as string
except Exception as e:
print(f" Error during signing/sending: {e}")
import traceback
traceback.print_exc()
return None
def confirm_transaction(tx_sig, rpc_client, commitment="confirmed", max_retries=10, delay_seconds=5):
"""Confirms the transaction on the network."""
print(f"5. Confirming transaction ({commitment})...")
retries = 0
while retries < max_retries:
try:
status_response = rpc_client.get_signature_statuses([tx_sig], search_transaction_history=True)
if status_response.value and status_response.value[0] is not None:
status = status_response.value[0]
if status.confirmation_status:
current_commitment = status.confirmation_status.name.lower() # Use .name for enum
print(f" Current confirmation status: {current_commitment}")
if current_commitment == commitment or \
(commitment == "confirmed" and current_commitment == "finalized") or \
(commitment == "processed" and (current_commitment in ["confirmed", "finalized"])):
if status.err:
print(f" Transaction failed: {status.err}")
return False
else:
print(f" Transaction successfully confirmed at {commitment} level!")
return True
else:
print(f" Status not yet available for {tx_sig}. Retrying ({retries + 1}/{max_retries})...")
except Exception as e:
print(f" Error checking transaction status: {e}")
retries += 1
time.sleep(delay_seconds)
print(f" Transaction confirmation timed out after {max_retries} retries.")
return False
# --- Main Execution ---
if __name__ == "__main__":
print("--- Solana Auto Swap Script (Jupiter API v6) ---")
print("\nWARNING: Providing your private key is a security risk.")
print("Use only with a burner wallet or small amounts.\n")
# 1. Get Inputs Securely
try:
# Use getpass to avoid showing the key on screen
private_key_b58 = getpass.getpass("Enter your wallet's private key (base58 encoded): ")
target_token_address = input(f"Enter the SPL token mint address to buy with {AMOUNT_SOL} SOL: ")
# Validate token address (basic check)
try:
target_token_pubkey = Pubkey.from_string(target_token_address)
except ValueError:
print("Error: Invalid target token mint address.")
exit(1)
#