Skip to main content
Code examples for common swap scenarios using the Stableswapper program.
These examples assume you’ve completed the Quickstart setup steps (dependencies, environment variables, and IDL/ABI).

Setup

Use these Base Sepolia addresses in your examples. For mainnet, replace with your production addresses from Key Addresses.

Swap USDC for custom token


Swap custom token for USDC


Swap to a different recipient

On Base, you can send swap output directly to another address by specifying a different recipient.

Query contract state

Read contract state before executing swaps for validation and fee calculation.

Split a large swap across available liquidity

A single swap reverts with AmountOutExceedsAvailableLiquidity if the output exceeds the pool’s available tokenOut liquidity (balance minus reserved). Split large amounts into chunks that each fit current liquidity; when the pool is temporarily short, wait and retry rather than failing — liquidity is replenished over time.
Re-read available liquidity before every chunk (it changes as others swap and as the pool refills) and cap each chunk at a fraction of it (CHUNK_BPS, 50% below) so no single tx drains the pool. A lower fraction is gentler on a contended pool — fewer race reverts — but uses more transactions; tune it to your pool’s contention.
This example waits indefinitely for refills. In production, bound the wait (a max retry count or deadline) so a request can’t hang forever, and surface progress to the caller.
Resuming after a crash. This loop tracks progress (remaining) in memory only — if the process dies mid-request, re-running from the original amount would over-swap. For unattended use, persist progress durably: after each confirmed chunk record how much has been swapped, and record a chunk’s tx hash before sending it. On restart, recompute remaining from the confirmed total and re-check that last tx hash to see whether it landed. The sign-once (fixed-nonce) send makes it safe to redo a chunk that didn’t land — it can’t produce a duplicate.

Swap between two custom stablecoins

The contract supports swapping between any two listed and swappable tokens — not just USDC pairs. To swap between two custom stablecoins, use their respective addresses as tokenIn and tokenOut. Both tokens must be listed and have swapping enabled.

Reference

Complete swap instruction parameters and accounts

Production Readiness

Helper functions and best practices

Quickstart

Get up and running in 10 minutes

Key Addresses

Program IDs and deployed addresses