How it works
When you perform a swap, OneBalance automatically:- Aggregates your balances across all supported chains
- Finds the best exchange rate from available liquidity sources
- Executes the swap using the optimal route
- Delivers the destination tokens to your account
Implementation
The swap feature is built using several key components:SwapForm component
The main swap interface is implemented incomponents/SwapForm.tsx. It manages the swap flow from quote retrieval to execution:
components/SwapForm.tsx
Getting quotes
Quotes are fetched using theuseQuotes hook, which communicates with the OneBalance API:
lib/hooks/useQuotes.ts
lib/types/quote.ts
Quote lifecycle
Quotes have a 30-second validity period. The application displays a countdown timer and automatically refreshes the quote when it expires:components/QuoteCountdown.tsx
Executing swaps
Once you have a valid quote, execute it by signing with your embedded wallet:Quote details
Each quote includes detailed information about the swap:- Exchange rate: How much of the destination token you’ll receive
- Price impact: The effect of your trade on the market price
- Route: Which chains and liquidity sources will be used
- Gas estimation: Approximate gas costs (covered by the paymaster)
All gas fees are abstracted away through OneBalance’s gasless transaction system. You don’t need to hold native tokens for gas.
Balance checking
The swap form automatically validates that you have sufficient balance before allowing execution:components/SwapForm.tsx
Supported assets
You can swap between any assets returned by the/v1/assets endpoint. The application dynamically loads available assets:
lib/hooks/useAssets.ts
Error handling
The swap interface handles various error states:- Insufficient balance: Button displays “Insufficient Balance”
- Expired quote: Automatically refreshes the quote
- Network errors: Shows error alert with retry option
- Invalid amounts: Validates numeric input in real-time
Best practices
Check balances first
Always verify you have sufficient balance before requesting a quote. The application does this automatically but you should check if building custom interfaces.
Monitor quote expiration
Quotes expire after 30 seconds. Use the countdown component and refresh quotes when needed.
Handle errors gracefully
Network issues can occur. Always implement retry logic and show clear error messages to users.