Complete demo available at onebalance-chain-abstracted-swap.vercel.app.
Open Source Example
All examples in this guide are 100% free and open-source. Clone the repository to quickly get started.
Core Architecture Overview
A successful chain-abstracted swap application requires understanding these key components:- Smart Account Prediction: Determine account addresses before deployment
- Quote Management: Real-time quote fetching with expiration handling
- Transaction Signing: EIP-712 typed data signing with Privy
- Status Monitoring: Real-time transaction status polling
- Balance Validation: Ensure sufficient funds before execution
Prerequisites
Before diving into building the cross-chain swap interface, you’ll need to have the following prerequisites in place:Development Environment
- Node.js 20+: Our project uses modern TypeScript features. Install using nvm or download from nodejs.org.
- pnpm: We’ll use pnpm as our package manager for its speed and efficiency. Install it by running
npm install -g pnpm
or follow the official installation guide.
Technical Knowledge
- Next.js App Router: Understanding of Next.js 15’s App Router architecture is essential for this project.
- React Hooks: Familiarity with React’s useState, useEffect, useCallback, and custom hooks.
- TypeScript: Basic knowledge of TypeScript types and interfaces.
- Tailwind CSS & shadcn/ui: We’ll use these for styling and components.
Privy Setup
To integrate Privy into your codebase, follow Privy’s Quickstart documentation. Once Privy is set up, ensure you have the following:- Privy App ID
- PrivyProvider configured on your client
- User login workflow organized and tested on the client side
Setting Up the Project
We will use Next.js 15 with app router & TypeScript for this project, along with Tailwind CSS for styling and shadcn/ui for components. Let’s initialize the project:terminal
terminal
Environment Setup
Make sure to copy.env.example
into .env
:
.env
Get your OneBalance API key from www.onebalance.io and Privy App ID from console.privy.io
1. Smart Account Integration
Understanding OneBalance Smart Accounts
OneBalance uses Smart Contract Accounts (SCAs) that can be predicted before deployment. This enables:- Receiving funds before the account exists on-chain
- Seamless transaction execution across chains
- Gas sponsorship and batched operations
Implementation Pattern
lib/api/account.ts
sessionAddress
and adminAddress
for simplicity. The predicted address becomes your user’s primary account identifier.
2. Quote Management & Lifecycle
Quote Request Structure
OneBalance quotes follow a specific request format that defines the swap parameters:Quote Lifecycle Management
The quote lifecycle involves several critical stages:- Validation: Check user balance before requesting quotes
- Expiration Handling: Quotes expire in 30 seconds - implement countdown timers
- Auto-refresh: Automatically fetch new quotes when current ones expire
- Debouncing: Prevent excessive API calls during user input
useQuotes.ts
):
3. Transaction Signing with Privy
EIP-712 Typed Data Signing
OneBalance transactions require signing structured data (EIP-712) for each chain operation. The signing process handles multiple operations sequentially. Key Implementation (fromprivySigningUtils.ts
):
- Each quote contains multiple
ChainOperation
objects that need individual signatures - Operations must be signed sequentially to avoid nonce conflicts
- The
typedDataToSign
field contains the EIP-712 structure for each operation
4. Transaction Execution Flow
Complete Transaction Workflow
- Quote Validation: Check expiration before execution
- Signing: Sign all required operations using Privy
- Execution: Submit signed quote to OneBalance
- Monitoring: Poll transaction status until completion
5. Real-Time Status Monitoring
Status Polling Implementation
After execution, implement real-time polling to track transaction progress:PENDING
: Transaction submitted to blockchainIN_PROGRESS
: Being processed across chainsCOMPLETED
: Successfully completedFAILED
: Transaction failedREFUNDED
: Funds returned to user
6. User Experience Enhancements
Quote Countdown Timer
Show users when quotes will expire:
7. Error Handling & Recovery
Graceful Error Management
Implement error handling for all failure scenarios:8. API Integration Patterns
Proxy Pattern for CORS
Use Next.js API routes to handle CORS and secure API keys:app/api/[...path]/route.ts
Key Integration Concepts
Chain Abstraction Benefits
- Unified Token Balances: Users see aggregated balances across all chains
- Automatic Routing: OneBalance finds optimal paths for swaps
- Gas Sponsorship: No need for users to hold native tokens for gas
- Network Abstraction: Users never need to think about which chain they’re using
Production Considerations
- Error Boundaries: Implement React error boundaries for graceful failures
- Rate Limiting: Implement client-side rate limiting for API calls
- Cache Management: Cache asset data and balance information appropriately
- Security: Never expose API keys in client-side code
The complete implementation demonstrates these patterns in production. Check the GitHub repository for detailed examples and best practices.