Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
node_modules
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
129 changes: 129 additions & 0 deletions API_INTEGRATION_README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
# 0x API Integration Setup

This project integrates with the 0x API for real-time swap pricing and quote generation. Follow these steps to set up the API integration:

## Environment Setup

1. **Get a 0x API Key**
- Visit [0x.org](https://0x.org/docs/introduction/getting-started)
- Sign up and get your API key

2. **Configure Environment Variables**
```bash
# Copy the example file
cp .env.local.example .env.local
```

Edit `.env.local` and add your API key:
```bash
NEXT_PUBLIC_ZERO_EX_API_KEY=your_api_key_here
NEXT_PUBLIC_DEFAULT_CHAIN_ID=1
NEXT_PUBLIC_ENABLE_SWAP_API=true
```

## Features Implemented

### ✅ Real-time Price Fetching
- Live price updates as you type amounts
- Support for multiple chains (Ethereum, Base, Polygon)
- Debounced API calls to prevent excessive requests

### ✅ Token Management
- Pre-configured token lists for popular tokens
- Support for ERC-20 tokens
- Automatic token validation

### ✅ Error Handling
- Network error handling
- API rate limit handling
- User-friendly error messages

### ✅ Loading States
- Price loading indicators
- Quote loading states
- Processing states during swaps

## API Integration Details

### Services Created:

1. **`src/services/zeroExApi.ts`** - Core API client
- `fetchSwapPrice()` - Get indicative pricing
- `fetchSwapQuote()` - Get firm quotes for execution
- Error handling and response validation

2. **`src/services/config.ts`** - Configuration management
- Environment variable handling
- Chain configuration
- Feature flags

3. **`src/services/tokenData.ts`** - Token and network data
- Supported token lists
- Network configurations
- Helper functions for token lookup

### Hook Updates:

**`src/hooks/useSwap.ts`** - Enhanced with API integration
- Real-time price fetching
- Debounced API calls
- State management for loading/errors
- Quote management

### Component Updates:

**`src/components/swap/TokenSelection.tsx`**
- Real-time price display
- Loading indicators
- Error handling UI
- Dynamic token information

## Usage

1. **Start the development server:**
```bash
npm run dev
```

2. **Enter swap details:**
- The app will automatically fetch prices as you type
- Real-time exchange rates are displayed
- Proceed through the swap flow

## API Endpoints Used

Based on the specifications in `llm.md`:

- **GET** `/swap/allowance-holder/price` - Indicative pricing
- **GET** `/swap/allowance-holder/quote` - Firm quotes

## Supported Networks

- **Ethereum (Chain ID: 1)** - ETH, USDC, USDT, WBTC, DAI, UNI
- **Base (Chain ID: 8453)** - ETH, USDC, DAI, WETH
- **Polygon (Chain ID: 137)** - MATIC, USDC, USDT, WETH

## Error Handling

The app handles various error scenarios:
- Missing API key
- Network connectivity issues
- Invalid token pairs
- API rate limits
- Insufficient liquidity

## Next Steps

To complete the swap functionality:
1. Add wallet connection (WalletConnect, MetaMask)
2. Implement transaction signing
3. Add transaction monitoring
4. Add slippage protection
5. Implement multi-chain support

## Development Notes

- API calls are debounced (500ms) to prevent excessive requests
- Prices are fetched automatically when amount/tokens change
- All monetary amounts are properly formatted for display
- Error states are clearly communicated to users
221 changes: 221 additions & 0 deletions RAINBOWKIT_INTEGRATION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
# RainbowKit Wallet Integration

This document covers the complete RainbowKit integration for wallet connectivity and transaction execution in the SwapInAd application.

## 🚀 Features Implemented

### ✅ **Wallet Connection**
- **RainbowKit Integration** - Modern wallet connection interface
- **Multiple Wallet Support** - MetaMask, WalletConnect, Coinbase Wallet, and more
- **Chain Switching** - Automatic network switching for supported chains
- **Custom Styling** - Dark theme matching the app's design

### ✅ **Multi-Chain Support**
- **Ethereum Mainnet** (Chain ID: 1)
- **Base** (Chain ID: 8453)
- **Polygon** (Chain ID: 137)
- Automatic token list updates based on selected chain

### ✅ **Real-Time Balance Display**
- Live wallet balance for selected tokens
- "MAX" button for quick amount selection
- Balance updates when switching tokens or chains

### ✅ **Transaction Execution**
- **Two-Step Process**: Token approval + Swap execution
- **Real-time Progress**: Live updates during transaction processing
- **Transaction Tracking**: Hash display with block explorer links
- **Error Handling**: Comprehensive error messages and recovery

### ✅ **Enhanced User Experience**
- Wallet connection status in header
- Chain indicator with switching capability
- Loading states during wallet operations
- Transaction progress visualization

## 📁 File Structure

```
src/
├── components/
│ ├── providers/
│ │ └── Providers.tsx # RainbowKit & Wagmi providers
│ ├── wallet/
│ │ └── WalletConnect.tsx # Custom wallet connect button
│ ├── layout/
│ │ └── Header.tsx # Header with wallet integration
│ └── swap/
│ ├── Processing.tsx # Enhanced processing with real tx status
│ └── ...
├── hooks/
│ ├── useSwap.ts # Enhanced with wallet integration
│ └── useSwapExecution.ts # Transaction execution logic
├── services/
│ ├── swapExecution.ts # Core transaction execution
│ └── ...
└── lib/
└── wagmi.ts # Wagmi configuration
```

## 🔧 Setup Instructions

### 1. **Environment Configuration**

Create/update your `.env.local` file:

```bash
# 0x API Configuration
NEXT_PUBLIC_ZERO_EX_API_KEY=your_0x_api_key

# WalletConnect Configuration
NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID=your_walletconnect_project_id

# Chain Configuration
NEXT_PUBLIC_DEFAULT_CHAIN_ID=1
NEXT_PUBLIC_ENABLE_SWAP_API=true
```

### 2. **Get WalletConnect Project ID**

1. Visit [WalletConnect Cloud](https://cloud.walletconnect.com)
2. Create a new project
3. Copy your Project ID
4. Add it to `.env.local`

### 3. **Dependencies Installed**

```bash
npm install @rainbow-me/rainbowkit wagmi viem@2.x @tanstack/react-query
```

## 🎯 Key Components

### **Providers Setup**
```typescript
// src/components/providers/Providers.tsx
<WagmiProvider config={config}>
<QueryClientProvider client={queryClient}>
<RainbowKitProvider theme={darkTheme}>
{children}
</RainbowKitProvider>
</QueryClientProvider>
</WagmiProvider>
```

### **Wallet Connection**
```typescript
// Custom wallet button with app styling
<ConnectButton.Custom>
{({ account, chain, openConnectModal, openAccountModal }) => (
// Custom UI matching app design
)}
</ConnectButton.Custom>
```

### **Swap Execution Flow**
1. **Price Fetching** - Real-time pricing with wallet address
2. **Quote Generation** - Firm quotes for connected wallet
3. **Token Approval** - ERC-20 approval if needed
4. **Swap Execution** - On-chain transaction execution
5. **Confirmation** - Transaction confirmation and success

## 🔄 Transaction Flow

### **Step 1: Token Selection & Pricing**
- User selects tokens and amount
- Real-time price fetching with wallet address as taker
- Balance display and MAX button integration

### **Step 2: Review & Confirm**
- Display swap details and estimated costs
- Quote generation with firm pricing
- Wallet connection validation

### **Step 3: Transaction Execution**
```typescript
const executeSwap = async (quote, fromToken) => {
// 1. Check & approve token allowance (if needed)
if (needsApproval) {
await approveToken(fromToken.address, quote.allowanceTarget);
}

// 2. Execute swap transaction
const txHash = await sendTransaction({
to: quote.to,
data: quote.data,
value: quote.value
});

// 3. Wait for confirmation
await waitForTransactionReceipt(txHash);
};
```

### **Step 4: Success & Completion**
- Transaction confirmation display
- Block explorer link for verification
- Option to start new swap

## 💡 Advanced Features

### **Chain Switching**
```typescript
const { switchChain } = useSwitchChain();

// Automatic chain switching for optimal routing
await switchChain({ chainId: targetChain });
```

### **Balance Integration**
```typescript
const { data: balance } = useBalance({
address: userAddress,
token: tokenAddress // undefined for native token
});
```

### **Transaction Monitoring**
```typescript
// Real-time progress updates
const progress = {
step: 'approval' | 'swap' | 'complete',
message: 'Current operation description',
transactionHash: '0x...'
};
```

## 🛡️ Security Considerations

- **API Key Security** - Never expose private keys in client code
- **Transaction Validation** - All transactions validated before execution
- **Slippage Protection** - Built-in slippage tolerance
- **Gas Estimation** - Proper gas estimation before transactions

## 🚧 Error Handling

The app handles various error scenarios:
- **Wallet Not Connected** - Prompts user to connect
- **Wrong Network** - Offers network switching
- **Insufficient Balance** - Clear error messages
- **Transaction Failures** - Retry mechanisms
- **API Errors** - Fallback messaging

## 🎨 UI/UX Features

- **Consistent Theming** - Dark theme matching app design
- **Loading States** - Visual feedback during operations
- **Progress Indicators** - Step-by-step transaction progress
- **Responsive Design** - Works on desktop and mobile
- **Accessibility** - Keyboard navigation and screen reader support

## 🔮 Future Enhancements

Potential improvements for production:
1. **Slippage Settings** - User-configurable slippage tolerance
2. **Gas Price Control** - Custom gas price settings
3. **Transaction History** - Local storage of past swaps
4. **Multi-Hop Routing** - Cross-chain swap support
5. **Price Alerts** - Token price notifications
6. **Advanced Orders** - Limit orders and DCA

The RainbowKit integration provides a complete, production-ready wallet connectivity solution with smooth transaction execution and excellent user experience.
36 changes: 36 additions & 0 deletions README copy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).

## Getting Started

First, run the development server:

```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.

This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.

## Learn More

To learn more about Next.js, take a look at the following resources:

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.

You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!

## Deploy on Vercel

The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.

Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
Loading