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

import requests import base64 import time import gzip import json from datetime import…

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

    import requests import base64 import time import gzip import json from datetime import datetime from io import BytesIO from solders.keypair import Keypair from solders.pubkey import Pubkey from solana.rpc.api import Client from solana.transaction import Transaction from solana.rpc.types import TxOpts

    === CONFIGURATION ===

    RPC_URL = "https://api.mainnet-beta.solana.com" JUPITER_API = "https://quote-api.jup.ag" COINSCAN_URL = "https://api.coinscan.com/v2/pair-explorer/1399811149/age/1h/0" SOL_MINT = "So11111111111111111111111111111111111111112" BUY_AMOUNT_LAMPORTS = int(0.0001 * 10**9) # 0.0001 SOL SELL_DELAY = 180 # 3 minutes MAX_RETRIES = 5

    === 1. DEMANDE CLÉ PRIVÉE UTILISATEUR ===

    secret_key = input("🔐 Entrez votre clé privée Solana (base58) : ").strip() keypair = Keypair.from_base58_string(secret_key) wallet_pubkey = keypair.pubkey() client = Client(RPC_URL)

    === 2. EXTRACTION DES TOKENS RÉCENTS (COINSCAN) ===

    def get_recent_tokens(): try: headers = { "User-Agent": "Mozilla/5.0", "Accept-Encoding": "gzip", "Accept": "/" } r = requests.get(COINSCAN_URL, headers=headers, timeout=10) r.raise_for_status() buf = BytesIO(r.content) data = gzip.GzipFile(fileobj=buf).read() tokens = json.loads(data) return tokens.get("data", {}).get("rows", []) except Exception as e: print(f"❌ Erreur Coinscan : {e}") return []

    === 3. FILTRER TOKENS DE MOINS DE 20s ===

    def filter_fresh_tokens(tokens): now = int(time.time()) fresh = [] for token in tokens: created = int(token.get("createdAt", 0)) if now - created <= 20: fresh.append({ "mint": token.get("baseHash"), "createdAt": created }) return fresh

    === 4. GET ROUTE ACHAT (JUPITER) ===

    def get_buy_route(output_mint): params = { "inputMint": SOL_MINT, "outputMint": output_mint, "amount": str(BUY_AMOUNT_LAMPORTS), "slippageBps": 50 } r = requests.get(f"{JUPITER_API}/v6/quote", params=params) r.raise_for_status() return r.json()["data"][0]

    === 5. GET ROUTE VENTE (JUPITER) ===

    def get_sell_route(input_mint, amount): params = { "inputMint": input_mint, "outputMint": SOL_MINT, "amount": str(amount), "slippageBps": 50 } r = requests.get(f"{JUPITER_API}/v6/quote", params=params) r.raise_for_status() return r.json()["data"][0]

    === 6. EXECUTER SWAP JUPITER ===

    def execute_swap(route_info): payload = { "route": route_info, "userPublicKey": str(wallet_pubkey), "wrapUnwrapSOL": True, "asLegacyTransaction": True } r = requests.post(f"{JUPITER_API}/v6/swap", json=payload) r.raise_for_status() tx_b64 = r.json()["swapTransaction"] tx_bytes = base64.b64decode(tx_b64) tx = Transaction.deserialize(tx_bytes) tx.sign([keypair]) txid = client.send_transaction(tx, keypair, opts=TxOpts(skip_preflight=True, skip_confirmation=False)) print(f"✅ Transaction envoyée : {txid['result']}") return txid['result']

    === 7. GET TOKEN BALANCE ===

    def get_token_balance(mint): headers = {"Content-Type": "application/json"} payload = { "jsonrpc": "2.0", "id": 1, "method": "getTokenAccountsByOwner", "params": [ str(wallet_pubkey), {"programId": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"}, {"encoding": "jsonParsed"} ] } r = requests.post(RPC_URL, json=payload, headers=headers) r.raise_for_status() accounts = r.json().get("result", {}).get("value", []) for acc in accounts: info = acc["account"]["data"]["parsed"]["info"] if info["mint"] == mint: return int(info["tokenAmount"]["amount"]) return 0

    === MAIN LOGIC ===

    def main(): print("🔍 Recherche de nouveaux tokens...") tokens = get_recent_tokens() fresh = filter_fresh_tokens(tokens)

    if not fresh:
        print("⛔ Aucun token récent trouvé (< 20s).")
        return
    
    token = fresh[0]
    mint = token["mint"]
    created = token["createdAt"]
    print(f"🆕 Token détecté : {mint} (créé il y a {int(time.time()) - created}s)")
    
    # === ACHAT ===
    for attempt in range(1, MAX_RETRIES + 1):
        try:
            print(f"🛒 Achat tentative {attempt}...")
            route = get_buy_route(mint)
            execute_swap(route)
            break
        except Exception as e:
            print(f"❌ Erreur achat : {e}")
            time.sleep(3)
    else:
        print("⛔ Achat échoué.")
        return
    
    # === ATTENTE 3 MIN ===
    target_time = created + SELL_DELAY
    wait_time = max(0, target_time - int(time.time()))
    print(f"⏳ Attente {wait_time}s avant vente...")
    time.sleep(wait_time)
    
    # === VENTE ===
    balance = get_token_balance(mint)
    if balance == 0:
        print("❌ Aucun token à vendre.")
        return
    
    for attempt in range(1, MAX_RETRIES + 1):
        try:
            print(f"💸 Vente tentative {attempt} de {balance} units...")
            route = get_sell_route(mint, balance)
            execute_swap(route)
            print("✅ Vente réussie.")
            break
        except Exception as e:
            print(f"❌ Erreur vente : {e}")
            time.sleep(3)
    else:
        print("⛔ Vente échouée après plusieurs tentatives.")
    

    === LANCEMENT ===

    if name == "main": main()

  2. Assistant

    Your Python script is designed to automate the process of detecting newly created tokens on the Solana blockchain and executing buy and sell transactions for these tokens. Here's a breakdown of its functionality:

    1. User Private Key Input: The script prompts you to enter your Solana private key in base58 format. This key is used to sign transactions.

    2. Fetching Recent Tokens: It retrieves data from Coinscan to identify tokens that have been created within the last 20 seconds.

    3. Filtering Fresh Tokens: The script filters out tokens that are older than 20 seconds, focusing only on the most recent ones.

    4. Obtaining Buy Route: Using the Jupiter API, it fetches the optimal route to swap SOL for the newly detected token.

    5. Executing the Swap: The script constructs and signs the transaction to execute the swap, then sends it to the Solana network.

    6. Waiting Period: After purchasing, the script waits for a predefined period (3 minutes by default) before proceeding to sell.

    7. Obtaining Sell Route: It fetches the optimal route to swap the purchased token back to SOL.

    8. Executing the Sell: The script constructs and signs the transaction to execute the sell, then sends it to the Solana network.

    Considerations and Recommendations:

    • Transaction Fees: Solana's network can experience congestion, leading to variable transaction fees. To ensure timely execution, consider implementing priority fees. This involves analyzing recent block data to determine an appropriate fee that increases the likelihood of your transaction being processed promptly[1].

    • Error Handling: The script includes retry mechanisms for both buy and sell operations, which is crucial for handling transient network issues or API rate limits. Ensure that these mechanisms are robust and consider implementing exponential backoff strategies to avoid overwhelming the network or APIs.

    • Security: Handling private keys requires utmost caution. Ensure that your private key is stored securely and never hard-coded into the script. Consider using environment variables or secure vaults to manage sensitive information.

    • API Rate Limits: Both Coinscan and Jupiter APIs may have rate limits. Monitor your usage to avoid being temporarily blocked. If you plan to scale this script, consider reaching out to the API providers for higher rate limits or dedicated access.

    • Testing: Before deploying this script on the mainnet, thoroughly test it on Solana's devnet. This allows you to identify and fix potential issues without risking real funds.

    • Monitoring: Implement logging and monitoring to track the script's performance and quickly identify any failures or anomalies. This is especially important for automated trading systems to ensure they operate as intended.

    For a more comprehensive understanding of integrating priority fees into your Solana transactions using Python, refer to the detailed guide provided by Chainstack[1].

    Additionally, the Solana Stack Exchange community has discussions and examples on performing swaps using the Jupiter API in Python, which might offer further insights[2].

    Remember, while automation can enhance trading efficiency, it's essential to stay informed about the latest developments in the Solana ecosystem and continuously monitor your scripts to adapt to any changes.

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