Implementing Token Swap in Mobile Crypto Wallet
Built-in swap is a wallet's competitive advantage. Users exchange tokens without leaving the app. But behind the simple UI lies a non-trivial chain: quote → slippage → approve → swap → tracking. Each step has potential user loss if implemented incorrectly.
Getting a Quote
A quote is how many tokens B the user gets for N tokens A accounting for pool commission. Sources:
1inch Aggregation Protocol API — most popular for multi-chain wallets. GET /v5.2/{chainId}/quote?src={tokenIn}&dst={tokenOut}&amount={amount} returns toAmount, estimatedGas, and route.
Uniswap V3 QuoterV2 — onchain quote via eth_call. Good if the wallet works with only one network and doesn't want external API dependency.
0x API (/swap/v1/quote) — good alternative to 1inch for EVM networks, especially Ethereum and Polygon.
Quotes age fast—refresh every 15–30 seconds, show countdown timer to the user. After expiry, auto-request a new one.
Slippage and amountOutMinimum
Slippage is the maximum acceptable deviation from the quote. amountOutMinimum = quotedAmount * (1 - slippage/100). If actual output is less, the transaction reverts.
// Android — calculate amountOutMinimum
val slippageBips = 50 // 0.5% in basis points
val amountOutMinimum = quotedAmountOut.multiply(BigInteger.valueOf(10000 - slippageBips))
.divide(BigInteger.valueOf(10000))
Show the user: "You'll receive minimum X.XX TOKEN." This is honest and reduces complaints during high volatility.
For stablecoin pairs (USDC → USDT), 0.1% slippage is enough. For low-liquidity meme tokens, manual control up to 5–10% with explicit risk warning.
Approve: Token Approval Before Swap
ERC-20 requires approve(spenderAddress, amount) before the router takes tokens. If allowance is already sufficient (allowance >= amountIn), skip it.
Check allowance: ERC20.allowance(ownerAddress, spenderAddress) via eth_call.
Two approaches to the amount:
- Exact amount (approve on amountIn): safer but requires approve on each swap.
- Max approve (
uint256.max): one transaction forever, but risk if the router is compromised.
In 2023–2024, several routers were hacked, and users with max approve lost funds. Recommend exact approve with "remember permission" option for power users.
Tracking and Swap History
After sending, show pending status with txHash. Poll eth_getTransactionReceipt every 5 seconds. On status status: 0 (revert), show the reason: decode revertReason from receipt or do eth_call with the same parameters to get the error.
Store swap history locally: tokenA → tokenB, amounts, txHash, timestamp, final status. Users should see past operations offline.
Timeline: 5 days: quote API integration, slippage calculation, approve → swap flow, transaction tracking, history. Multi-chain swap (ETH + BSC + Polygon): +2–3 days.







