Efficient Token Swaps with Slippage Control

This page provides a guide to performing efficient token swaps on Solana using Jupiter Exchange, complete with slippage control for precise execution.

Overview

The TradeManager class enables seamless token swaps through Jupiter Exchange by providing:

  • Flexible Inputs: Swap between various tokens, including USDC and SOL.

  • Slippage Control: Fine-tune transactions with customizable slippage tolerance.

  • Reliable Transaction Execution: Ensures accurate blockhash management and transaction confirmation.


Code Explanation

1. Quoting a Swap

The trade method begins by fetching a quote for the desired token swap:

  • Sends a GET request to Jupiter's API with input/output token mints, input amount, and slippage tolerance.

  • Retrieves quote data for further processing.

Copy

quote_url = (
    f"{JUP_API}/quote?"
    f"inputMint={input_mint}"
    f"&outputMint={output_mint}"
    f"&amount={int(input_amount * LAMPORTS_PER_SOL)}"
    f"&slippageBps={slippage_bps}"
    f"&onlyDirectRoutes=true"
    f"&maxAccounts=20"
)

2. Fetching the Swap Transaction

After obtaining a quote, the method:

  • Sends a POST request with the quote and user information to fetch a prebuilt swap transaction.

  • Validates the swap transaction response.

Copy

async with session.post(
    f"{JUP_API}/swap",
    json={ "quoteResponse": quote_data, "userPublicKey": str(agent.wallet_address), ... },
) as swap_response:
    swap_data = await swap_response.json()

3. Signing and Sending the Transaction

The retrieved swap transaction is:

  • Deserialized and updated with the latest blockhash for validity.

  • Signed locally using the agent’s wallet.

  • Sent to the blockchain for execution.

Copy

swap_transaction_buf = base64.b64decode(swap_data["swapTransaction"])
transaction = VersionedTransaction.deserialize(swap_transaction_buf)
transaction.sign([agent.wallet])
signature = await agent.connection.send_raw_transaction(transaction.serialize())

4. Confirming the Transaction

The transaction is confirmed to ensure successful execution:

Copy

await agent.connection.confirm_transaction(
    signature, commitment=Confirmed, last_valid_block_height=latest_blockhash.value.last_valid_block_height
)

Key Features

  1. Customizable Slippage Control Set slippage tolerance in basis points (bps) to protect against significant price movements during swaps.

  2. Dynamic Quote Retrieval Retrieve quotes dynamically based on market conditions and user preferences.

  3. Prebuilt Swap Transactions Use Jupiter's API to fetch ready-to-execute transactions for streamlined processing.

  4. Reliable Transaction Handling Handle recent blockhash updates, local signing, and transaction confirmation for end-to-end reliability.


How to Use

  • Setup: Initialize SolanaAgentKit with your wallet and configure necessary constants like JUP_API.

  • Example Swap: Swap 10 USDC for SOL with 1% slippage.

    Copy

    from solders.pubkey import Pubkey  
    
    output_mint = Pubkey("So11111111111111111111111111111111111111112")  # SOL mint
    signature = await TradeManager.trade(agent, output_mint, 10, slippage_bps=100)
    print(f"Swap successful: {signature}")

Error Handling

  • Invalid API Responses: Ensure all API responses are validated for HTTP status codes and content integrity.

  • Transaction Failures: Retry mechanisms and error messages provide clarity in case of failures.

  • Blockhash Expiry: Refresh blockhash dynamically to prevent transaction expiration.

Last updated