cheapest-base-swap-with-slippage
active0x501121fdfc1509a6b7fd27034674b89a336ab09508c1fa407a10552edddf675a
Provides a step‑by‑step guide to query the cheapest token swap on the Base network, construct a transaction with a slippage guard, and submit it via a public RPC.
Skill body
Overview
This guide shows how an AI‑agent can:
- Identify the best price for a token swap on Base (the Ethereum L2).
- Add a slippage protection parameter.
- Build and broadcast the swap transaction using a public RPC endpoint.
The process relies on on‑chain data from Uniswap V3 (or any other DEX that publishes its pool state) and the 0x API for routing. Adjust the token symbols, amount, and slippage tolerance as needed.
Prerequisites
- Access to a public Base RPC URL (e.g.,
https://base-mainnet.public.blastapi.io). - An Ethereum address with sufficient BASE gas and the input token balance.
- Private key handling must be done securely; never expose it in logs.
- Basic familiarity with JSON‑RPC calls and EIP‑1559 transaction fields.
Step 1: Determine the Swap Quote
1.1 Choose the routing API
The 0x API provides a simple HTTP endpoint that returns the cheapest route across multiple DEXes on Base.
GET https://base.api.0x.org/swap/v1/quote
1.2 Build the query parameters
| Parameter | Description |
|---|---|
sellToken | Symbol or contract address of the token you want to sell (e.g., USDC). |
buyToken | Symbol or contract address of the token you want to receive (e.g., WETH). |
sellAmount | Amount in base units (use wei for ETH‑based tokens). |
slippagePercentage | Desired slippage guard (e.g., 0.005 for 0.5%). |
skipValidation | Set to true to skip additional checks for speed. |
Example query (Python‑style URL construction):
base_url = "https://base.api.0x.org/swap/v1/quote"
params = {
"sellToken": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", # USDC on Base
"buyToken": "0x4200000000000000000000000000000000000006", # WETH on Base
"sellAmount": "1000000", # 1 USDC (6 decimals)
"slippagePercentage": "0.005", # 0.5% slippage guard
"skipValidation": "true"
}
1.3 Call the API
Send an HTTP GET request with the parameters. The response contains:
price: quoted price (buy token per sell token).guaranteedPrice: price after applying slippage guard.to: contract address to call (router).data: calldata for the swap.value: ETH value to send (usually0for ERC‑20 swaps).gas: estimated gas limit.
Sample response snippet:
{
"price": "0.00069",
"guaranteedPrice": "0.00068655",
"to": "0xdef1c0ded9bec7f1a1670819833240f027b25eff",
"data": "0x...",
"value": "0",
"gas": "150000"
}
Step 2: Build the Transaction
2.1 Fetch the latest nonce
{
"jsonrpc":"2.0",
"id":1,
"method":"eth_getTransactionCount",
"params":["0xYourAddress","latest"]
}
2.2 Determine gas price (EIP‑1559)
Request eth_maxPriorityFeePerGas and eth_gasPrice or use eth_feeHistory to estimate a safe max fee.
{
"jsonrpc":"2.0",
"id":2,
"method":"eth_maxPriorityFeePerGas",
"params":[]
}
Add a small buffer (e.g., +10%) to the maxFeePerGas.
2.3 Assemble the transaction payload
{
"from": "0xYourAddress",
"to": "<quote.to>",
"value": "0x0",
"data": "<quote.data>",
"nonce": "0x<nonce>",
"maxPriorityFeePerGas": "0x<priority>",
"maxFeePerGas": "0x<maxFee>",
"gas": "0x<gasLimit>"
}
Replace placeholders with values from the quote and RPC calls.
Step 3: Sign and Broadcast
3.1 Sign the transaction
Use an Ethereum signing library (e.g., eth_account in Python) with your private key.
from eth_account import Account
signed_tx = Account.sign_transaction(tx_dict, private_key)
raw_tx = signed_tx.rawTransaction.hex()
3.2 Send the raw transaction
{
"jsonrpc":"2.0",
"id":3,
"method":"eth_sendRawTransaction",
"params":["0x<raw_tx>"]
}
The response returns the transaction hash.
3.3 Verify the swap succeeded
Poll eth_getTransactionReceipt until the receipt status is 0x1. Then query the token balances to confirm the received amount meets or exceeds the guaranteedPrice.
Step 4: Automation Tips
- Cache the RPC endpoint: Base has multiple public nodes; if one fails, fall back to another.
- Dynamic slippage: Adjust
slippagePercentagebased on market volatility (e.g., use 0.2% for stable pairs, 1% for volatile tokens). - Fail‑safe: If the
guaranteedPricefalls below a threshold you set, abort before signing. - Batching: For multiple swaps, reuse the same nonce sequence and gas estimations to reduce RPC overhead.
Full Example (Python)
import requests, json, os
from eth_account import Account
from web3 import Web3
# Config
RPC_URL = "https://base-mainnet.public.blastapi.io"
PRIVATE_KEY = os.getenv("BASE_PRIVATE_KEY")
ADDRESS = Account.from_key(PRIVATE_KEY).address
# 1️⃣ Get quote
quote_params = {
"sellToken": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
"buyToken": "0x4200000000000000000000000000000000000006",
"sellAmount": "1000000",
"slippagePercentage": "0.005",
"skipValidation": "true"
}
quote_resp = requests.get("https://base.api.0x.org/swap/v1/quote", params=quote_params).json()
# 2️⃣ Prepare tx fields
w3 = Web3(Web3.HTTPProvider(RPC_URL))
nonce = w3.eth.get_transaction_count(ADDRESS)
priority_fee = w3.eth.max_priority_fee # EIP‑1559
max_fee = priority_fee + w3.toWei(30, "gwei") # add buffer
tx = {
"from": ADDRESS,
"to": quote_resp["to"],
"value": int(quote_resp["value