This guide provides a step-by-step explanation for using the SolanaPortal API to execute token swaps with Python. Whether you're performing a standard token swap or a more complex Jito bundle transaction, this tutorial walks you through the process on how to swap using Node.js. We'll break down everything from setting up your environment to sending transactions.
Installing Prerequisites
Before you begin, ensure the following:
Python installed:
Download and install Python 3.8 or later from . Check your version with:
python --version
Private Key:
Obtain the private key for your Solana wallet (Phantom Wallet). Keep this key secure as it is required to sign transactions.
Setting Up the Environment
Create a new Python file named swap.py and open it in your code editor.
Install the required libraries:
pip install requests base58 solana
requests: For making HTTP requests to the API.
base58: For decoding wallet private keys.
solana: For interacting with the Solana blockchain.
Add the necessary imports or required libraries and initialize the wallet with your private key:
import requests
import base58
from solana.keypair import Keypair
from solana.transaction import Transaction
from solana.rpc.async_api import AsyncClient
from solana.rpc.types import TxOpts
# Initialize Wallet
private_key = "your-private-key-here" # Replace with your wallet's private key
wallet = Keypair.from_secret_key(base58.b58decode(private_key))
print("Wallet Address:", wallet.public_key)
Performing a Standard Token Swap
A standard token swap involves using a single wallet to trade one token on a supported decentralized exchange (DEX).
Full code example
import requests
import base58
from solana.keypair import Keypair
from solana.transaction import Transaction
# Initialize Wallets
wallets = [
Keypair.from_secret_key(base58.b58decode("your-private-key-1")),
Keypair.from_secret_key(base58.b58decode("your-private-key-2")),
]
# Define swaps for the bundle
bundle_params = [
{
"wallet_address": str(wallets[0].public_key),
"mint": "GAT41Hbuq2QVFKJZZGrALegyU2UKsPApkNGSoS2TjTGR",
"action": "buy",
"dex": "jupiter",
"amount": 0.001,
"tip": 0.0001,
},
{
"wallet_address": str(wallets[1].public_key),
"mint": "GAT41Hbuq2QVFKJZZGrALegyU2UKsPApkNGSoS2TjTGR",
"action": "sell",
"dex": "raydium",
"amount": 0.002,
"tip": 0.0002,
},
]
url = "https://api.solanaportal.io/api/jito-bundle"
# Send the POST request to the API
response = requests.post(url, json=bundle_params)
if response.status_code == 200:
data = response.json()
# Sign and broadcast each transaction in the bundle
signed_transactions = []
for i, txn_data in enumerate(data):
txn_buffer = base58.b58decode(txn_data)
txn = Transaction.deserialize(txn_buffer)
txn.sign(wallets[i])
signed_transactions.append(base58.b58encode(txn.serialize()).decode())
# Submit the bundle
jito_response = requests.post(
"https://tokyo.mainnet.block-engine.jito.wtf/api/v1/bundles",
json={
"jsonrpc": "2.0",
"id": 1,
"method": "sendBundle",
"params": [signed_transactions],
},
)
if jito_response.status_code == 200:
for i, signature in enumerate(jito_response.json()["result"]):
print(f"Transaction {i}: https://solscan.io/tx/{signature}")
else:
print("Jito Error Response:", jito_response.text)
else:
print("API Error:", response.text)
Performing a Jito Bundle Swap
For Jito bundles, you can batch multiple swaps into a single transaction. Each swap must have its own parameters, and you can use one or more wallets.
A single failed transaction in a Jito Bundle swap will cause the entire bundle to fail. Ensure all parameters and wallets are correctly configured to avoid issues
Full code example
import requests
import base58
from solana.keypair import Keypair
from solana.transaction import Transaction
# Initialize Wallets
wallets = [
Keypair.from_secret_key(base58.b58decode("your-private-key-1")),
Keypair.from_secret_key(base58.b58decode("your-private-key-2")),
]
# Define swaps for the bundle
bundle_params = [
{
"wallet_address": str(wallets[0].public_key),
"mint": "GAT41Hbuq2QVFKJZZGrALegyU2UKsPApkNGSoS2TjTGR",
"action": "buy",
"dex": "jupiter",
"amount": 0.001,
"tip": 0.0001,
},
{
"wallet_address": str(wallets[1].public_key),
"mint": "GAT41Hbuq2QVFKJZZGrALegyU2UKsPApkNGSoS2TjTGR",
"action": "sell",
"dex": "raydium",
"amount": 0.002,
"tip": 0.0002,
},
]
url = "https://api.solanaportal.io/api/jito-bundle"
# Send the POST request to the API
response = requests.post(url, json=bundle_params)
if response.status_code == 200:
data = response.json()
# Sign and broadcast each transaction in the bundle
signed_transactions = []
for i, txn_data in enumerate(data):
txn_buffer = base58.b58decode(txn_data)
txn = Transaction.deserialize(txn_buffer)
txn.sign(wallets[i])
signed_transactions.append(base58.b58encode(txn.serialize()).decode())
# Submit the bundle
jito_response = requests.post(
"https://tokyo.mainnet.block-engine.jito.wtf/api/v1/bundles",
json={
"jsonrpc": "2.0",
"id": 1,
"method": "sendBundle",
"params": [signed_transactions],
},
)
if jito_response.status_code == 200:
for i, signature in enumerate(jito_response.json()["result"]):
print(f"Transaction {i}: https://solscan.io/tx/{signature}")
else:
print("Jito Error Response:", jito_response.text)
else:
print("API Error:", response.text)
Running the Code
To run the code, follow these steps:
Save the code in a file named swap.py inside your project directory.
Run the file:
python swap.py
Ensure you have all dependencies installed and your private keys are configured correctly.
Key Notes
Jito Bundle Limitation: A single failed transaction in a bundle will fail the entire bundle.
Environment Setup: Ensure you are connected to the Solana mainnet.
Security: Never hardcode sensitive information like private keys in production code. Use environment variables or secret management tools.
Error Handling: Always validate API responses and handle errors gracefully.