Skip to main content
This example prepares native ETH → ERC-20 through provider=route. It checks the current zero-fee configuration, gets a simulated quote, sets the minimum received and verifies the returned transaction data. It stops before signing or sending anything. Use the public API at https://api.route.fun. For local testing, pass your local API base instead. Install viem in your own integration project and save the following module as prepare-swap.mjs.
Call prepareNativeSwap with the connected wallet’s public address, an ERC-20 output address and an input such as "100000000000000" for 0.0001 ETH. No private key belongs in this module or on your backend. Do not pass netAmountOut as the minimum: it is a gas-cost model, not the contract’s token payout. Do not use WETH as the output of this native-input recipe: ETH↔WETH is wrapping and is not a supported V2 swap pair. Show the swap details to the user, then follow the wallet flow. If the quote expires, get a fresh one and ask the user to review it. Keep their accepted minimum unless they agree to change it.

Add other swap types

For ERC-20 input, read allowance and handle the returned exact approval before refreshing. For Kyber and 0x, preserve the selected provider and variant, send branches: [], resolve the output-specific executor and validate that provider’s ABI. For 0x, txOrigin must be the signing EOA. The direct ABI in this recipe must not be reused to validate an upstream transaction. See swap request fields and the full schema. The zero-fee checks will stop this example when the fee policy changes. Follow the fee migration recipe to update those checks for the new contract and fee fields.