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
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
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
4. Confirming the Transaction
The transaction is confirmed to ensure successful execution:
Copy
Key Features
Customizable Slippage Control Set slippage tolerance in basis points (bps) to protect against significant price movements during swaps.
Dynamic Quote Retrieval Retrieve quotes dynamically based on market conditions and user preferences.
Prebuilt Swap Transactions Use Jupiter's API to fetch ready-to-execute transactions for streamlined processing.
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
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.