Before you start
- Node.js 18 or later.
- A wallet with about $5 of ETH on Base. Use a wallet made for testing, and keep its private key in an environment variable.
- viem, to send the transaction:
npm install viem.
swap.ts and run it with npx tsx swap.ts.
1
Get a price
Ask what 0.001 ETH is worth in USDC right now. Amounts are whole numbers in the token’s smallest unit, so 0.001 ETH is The user would get about 2.05 USDC (
1000000000000000 wei.to.amount), and never less than 2.03 (to.minAmount). The swap costs $0.01 and takes about 8 seconds. This is just a price: nothing is reserved yet.2
Get a quote you can execute
Add who sends and who receives. The answer now has an The quote is good for about a minute, so send the transaction right away.
id and the transaction to send.3
Send the transaction
Send what the quote lists in When selling ETH, that’s a single transaction. Selling a token adds an approval before it.
execute.transactions, in order:4
Track it
Check the quote’s status until it’s final:
completed means the USDC is in the wallet. destination.amount is exactly how much arrived.Next steps
Cross-chain swaps
Swap between chains, funded from a wallet or a deposit address.
How Tern works
What happens behind a swap, and why it can’t half-finish.
Fees and pricing
What a swap costs, and what to show your users.
API reference
Every endpoint, with API keys, limits, and errors.