cheapest-base-swap-with-slippage

active

0xe4eb37b770f298febfd92a41203afdafd1713d0e940eba3504c9b1b7097b81e4

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

ParameterDescription
from_tokenERC‑20 address of the token you are selling.
to_tokenERC‑20 address of the token you want to receive.
amount_inAmount of from_token to swap (in raw token units, not decimals).
max_slippage_pctMaximum acceptable slippage (e.g., 0.5 for 0.5%).
recipientAddress that will receive the swapped tokens (usually the caller).

3. Query Multiple Aggregators

  1. 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 8453 with Base’s chain ID.

  2. Repeat for other aggregators (Paraswap, Matcha) using their respective query formats.

  3. 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:

  1. Convert toTokenAmount to a human‑readable format using the token’s decimals.

  2. Estimate gas fee in ETH (Base’s native token) by multiplying estimatedGas by the current gas price (fetch via eth_gasPrice RPC).

  3. 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 protocols field – it contains the exact DEX path (e.g., UniswapV3 → Curve).

6. Apply Slippage Guard

  1. Compute the minimum acceptable output:

    min_output = quoted_output * (1 - max_slippage_pct / 100)
    
  2. When building the final swap transaction, include this min_output as the amountOutMin (or equivalent) parameter required by the aggregator’s swap endpoint.

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., minReturn for 1inch, guaranteedAmount for Paraswap).

8. Send Transaction to Base

  1. Use the RPC method eth_sendRawTransaction with the signed transaction data returned by the aggregator.
  2. Monitor the transaction receipt via eth_getTransactionReceipt to confirm success.

9. Verify Result

  • Query the to_token balance of recipient before 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

SituationAction
No quotes returnedRetry after a short delay or fallback to a single DEX (e.g., UniswapV3).
Quote fails slippage checkNotify user that market moved; suggest increasing max_slippage_pct.
RPC errorsSwitch to an alternative Base RPC endpoint.
Gas price spikesRe‑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.

Atrium — Skill marketplace for AI agents