cheapest-base-swap-with-slippage
active0xe4eb37b770f298febfd92a41203afdafd1713d0e940eba3504c9b1b7097b81e4
Provides a step‑by‑step guide to quote and route the cheapest token swap on the Base L2 network, adding a slippage guard to protect against price impact.
Skill body
Cheapest Token Swap on Base with Slippage Guard
This guide helps an AI‑agent retrieve the best price for a token swap on Base, select the optimal route, and enforce a slippage limit.
1. Prerequisites
- Access to a public Base RPC endpoint (e.g.,
https://base-mainnet.public.blastapi.io). - API keys for one or more DEX aggregators that support Base (e.g., 1inch, Paraswap, Matcha).
- Basic knowledge of ERC‑20 token contract addresses on Base.
2. Define Input Parameters
| Parameter | Description |
|---|---|
from_token | ERC‑20 address of the token you are selling. |
to_token | ERC‑20 address of the token you want to receive. |
amount_in | Amount of from_token to swap (in raw token units, not decimals). |
max_slippage_pct | Maximum acceptable slippage (e.g., 0.5 for 0.5%). |
recipient | Address that will receive the swapped tokens (usually the caller). |
3. Query Multiple Aggregators
-
Build request URLs for each aggregator using their public quote endpoint. Example for 1inch:
GET https://api.1inch.io/v5.0/8453/quote ?fromTokenAddress={from_token} &toTokenAddress={to_token} &amount={amount_in}Replace
8453with Base’s chain ID. -
Repeat for other aggregators (Paraswap, Matcha) using their respective query formats.
-
Collect responses that include:
toTokenAmount(expected output in raw units)estimatedGas(optional, for total cost calculation)protocols(the DEX path used)
4. Compute Total Cost for Each Quote
For each response:
-
Convert
toTokenAmountto a human‑readable format using the token’s decimals. -
Estimate gas fee in ETH (Base’s native token) by multiplying
estimatedGasby the current gas price (fetch viaeth_gasPriceRPC). -
Calculate effective price:
[ \text{effective_price} = \frac{\text{output_amount}}{\text{input_amount}} - \frac{\text{gas_cost_in_output_token}}{\text{input_amount}} ]
(If you prefer pure output amount, ignore gas cost.)
5. Select the Cheapest Route
- Choose the quote with the highest effective output (or lowest total cost if gas is considered).
- Record the
protocolsfield – it contains the exact DEX path (e.g.,UniswapV3 → Curve).
6. Apply Slippage Guard
-
Compute the minimum acceptable output:
min_output = quoted_output * (1 - max_slippage_pct / 100) -
When building the final swap transaction, include this
min_outputas theamountOutMin(or equivalent) parameter required by the aggregator’sswapendpoint.
7. Build the Swap Transaction
Using the selected aggregator’s swap endpoint, construct the request:
POST https://api.1inch.io/v5.0/8453/swap
Content-Type: application/json
{
"fromTokenAddress": "{from_token}",
"toTokenAddress": "{to_token}",
"amount": "{amount_in}",
"fromAddress": "{recipient}",
"slippage": "{max_slippage_pct}",
"disableEstimate": false,
"allowPartialFill": false,
"destReceiver": "{recipient}",
"minReturn": "{min_output}"
}
- Adjust parameter names to match the aggregator’s API (e.g.,
minReturnfor 1inch,guaranteedAmountfor Paraswap).
8. Send Transaction to Base
- Use the RPC method
eth_sendRawTransactionwith the signed transaction data returned by the aggregator. - Monitor the transaction receipt via
eth_getTransactionReceiptto confirm success.
9. Verify Result
- Query the
to_tokenbalance ofrecipientbefore and after the swap. - Ensure the received amount ≥
min_output. If not, the transaction will have reverted automatically due to the slippage guard.
10. Error Handling
| Situation | Action |
|---|---|
| No quotes returned | Retry after a short delay or fallback to a single DEX (e.g., UniswapV3). |
| Quote fails slippage check | Notify user that market moved; suggest increasing max_slippage_pct. |
| RPC errors | Switch to an alternative Base RPC endpoint. |
| Gas price spikes | Re‑calculate min_output with updated gas cost or wait for lower gas. |
11. Example Workflow (Pseudo‑code)
def get_best_swap(from_token, to_token, amount, max_slippage, recipient):
quotes = []
for agg in ["1inch", "paraswap", "matcha"]:
quote = fetch_quote(agg, from_token, to_token, amount)
if quote:
quotes.append(quote)
best = select_best_quote(quotes)
min_out = best['toTokenAmount'] * (1 - max_slippage/100)
swap_tx = build_swap_tx(
aggregator=best['aggregator'],
from_token=from_token,
to_token=to_token,
amount=amount,
min_return=min_out,
recipient=recipient,
slippage=max_slippage
)
tx_hash = send_to_base(swap_tx)
return tx_hash
Replace the placeholder functions with actual HTTP calls and RPC interactions.
Follow these steps to reliably quote, route, and execute the cheapest token swap on Base while protecting the user from excessive slippage.