hadv / hadv/ethaura

Feature: Token Swap Integration via KyberSwap Aggregator API

Open
#97 0 comments 0 reactions 0 assignees View on GitHub
enhancement swap 𐒾 KyberSwap
Dominant language
JavaScript
Stars
2
Forks
0
PR merge metrics
No merged PRs in 30d

Description

## 🎯 Overview

Integrate KyberSwap Aggregator API to enable users to swap tokens directly, seamlessly, and safely within their EthAura smart accounts. This will allow users to exchange tokens at the best available rates across multiple DEXs without leaving the wallet interface.

## πŸ“‹ Background

KyberSwap Aggregator is a DEX aggregator that:
- Finds the best swap routes across 100+ DEXs
- Splits trades across multiple liquidity sources for optimal pricing
- Supports all major EVM chains (Ethereum, Polygon, Arbitrum, Optimism, etc.)
- Provides a simple REST API for integration
- Handles complex routing and gas optimization automatically

**API Documentation**: https://docs.kyberswap.com/kyberswap-solutions/kyberswap-aggregator/developer-guides/execute-a-swap-with-the-aggregator-api

## πŸ”§ Technical Implementation

### API Endpoints (v1)

#### 1. Get Swap Route
```
GET https://aggregator-api.kyberswap.com/{chain}/api/v1/routes
```
**Parameters:**
- `tokenIn`: Source token address
- `tokenOut`: Destination token address
- `amountIn`: Amount to swap (in wei)
- `saveGas`: Optional gas optimization flag
- `gasInclude`: Include gas costs in route calculation

**Returns:**
- `routeSummary`: Best route with pricing and gas estimates
- `routerAddress`: Router contract address to execute swap

#### 2. Build Swap Transaction
```
POST https://aggregator-api.kyberswap.com/{chain}/api/v1/route/build
```
**Body:**
```json
{
"routeSummary": { /* from step 1 */ },
"sender": "0x...",
"recipient": "0x...",
"slippageTolerance": 50 // 0.5% in bips
}
```

**Returns:**
- `data`: Encoded calldata for the swap transaction
- `routerAddress`: Contract to call
- `value`: ETH value to send (for native token swaps)

### Integration Architecture

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ EthAura UI β”‚
β”‚ (React/Vite) β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚
β”œβ”€β”€β”€ 1. User selects tokens & amount
β”‚
β”œβ”€β”€β”€ 2. Query KyberSwap API for best route
β”‚ GET /routes
↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ KyberSwap API β”‚
β”‚ (Aggregator) β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚
β”œβ”€β”€β”€ 3. Return route summary with pricing
β”‚
β”œβ”€β”€β”€ 4. Build transaction calldata
β”‚ POST /route/build
↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ P256AccountSDK β”‚
β”‚ (Frontend) β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚
β”œβ”€β”€β”€ 5. Create UserOperation with swap calldata
β”‚
β”œβ”€β”€β”€ 6. Sign with Passkey (2FA if enabled)
β”‚
↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ ERC-4337 β”‚
β”‚ Bundler β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚
β”œβ”€β”€β”€ 7. Submit UserOp to EntryPoint
β”‚
↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ P256Account β”‚
β”‚ Smart Account β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚
β”œβ”€β”€β”€ 8. Execute swap via KyberSwap Router
β”‚
↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ KyberSwap β”‚
β”‚ Router β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚
└─── 9. Execute optimal swap route across DEXs
```

## πŸ› οΈ Implementation Tasks

### Phase 1: Backend Service (Optional - for API key management)
- [ ] Create `swapService.js` in `frontend/src/lib/`
- [ ] Implement KyberSwap API client with error handling
- [ ] Add rate limiting and caching for route queries
- [ ] Support multiple chains (Sepolia, Mainnet, Polygon, etc.)

### Phase 2: Smart Contract Integration
- [ ] Add token approval flow for ERC20 swaps
- Check current allowance for KyberSwap router
- Create approval transaction if needed
- Execute via P256Account's `execute()` function
- [ ] Implement swap execution via `execute()` or `executeBatch()`
- For single swap: `execute(routerAddress, value, swapCalldata)`
- For approval + swap: `executeBatch([tokenAddress, routerAddress], [0, value], [approvalData, swapCalldata])`

### Phase 3: Frontend UI
- [ ] Create `SwapScreen.jsx` component
- Token selection (from/to) with balance display
- Amount input with max button
- Slippage tolerance settings (default 0.5%)
- Route preview showing:
- Expected output amount
- Price impact
- Gas estimate
- Route path (which DEXs)
- [ ] Add swap button to `WalletDetailScreen`
- [ ] Implement swap confirmation modal
- Show final amounts and fees
- Require passkey signature
- Display transaction progress

### Phase 4: Security & UX
- [ ] **Token Approval Safety**
- Use exact approval amounts (not unlimited)
- Reset approval to 0 before setting new amount (for USDT compatibility)
- Show approval transaction separately in UI
- [ ] **Slippage Protection**
- Default to 0.5% slippage tolerance
- Warn users if slippage > 1%
- Allow custom slippage settings
- [ ] **Price Impact Warnings**
- Show warning if price impact > 3%
- Require confirmation if price impact > 5%
- [ ] **Transaction Simulation**
- Use `eth_call` to simulate swap before execution
- Detect and display potential failures
- [ ] **Error Handling**
- Handle insufficient balance
- Handle insufficient liquidity
- Handle failed approvals
- Handle slippage exceeded errors

### Phase 5: Testing
- [ ] Test on Sepolia testnet
- ETH β†’ USDC swap
- USDC β†’ ETH swap
- Token β†’ Token swap
- [ ] Test with 2FA enabled accounts
- [ ] Test approval + swap batch transaction
- [ ] Test slippage protection
- [ ] Test with different gas settings

## πŸ“Š Data Flow Example

### Swap 1 ETH β†’ USDC on Polygon

**Step 1: Get Route**
```javascript
const route = await fetch(
'https://aggregator-api.kyberswap.com/polygon/api/v1/routes?' +
'tokenIn=0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619' + // WETH
'&tokenOut=0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174' + // USDC
'&amountIn=1000000000000000000' // 1 ETH in wei
)
```

**Step 2: Build Transaction**
```javascript
const tx = await fetch(
'https://aggregator-api.kyberswap.com/polygon/api/v1/route/build',
{
method: 'POST',
body: JSON.stringify({
routeSummary: route.data.routeSummary,
sender: accountAddress,
recipient: accountAddress,
slippageTolerance: 50 // 0.5%
})
}
)
```

**Step 3: Execute via P256Account**
```javascript
const receipt = await sdk.executeTransaction({
accountAddress,
targetAddress: tx.data.routerAddress,
value: tx.data.value || 0,
callData: tx.data.data,
passkeyCredential,
signWithPasskey
})
```

## πŸ”’ Security Considerations

### 1. **Smart Contract Security**
- βœ… KyberSwap contracts are audited by leading firms
- βœ… Router contracts are non-upgradeable and battle-tested
- βœ… No token custody - atomic swaps only

### 2. **ERC-4337 Compatibility**
- βœ… Swap executes via `P256Account.execute()` - requires passkey signature
- βœ… All security guarantees of EthAura remain intact:
- Passkey required for all transactions
- 2FA support (passkey + owner signature)
- Guardian recovery available
- Timelock protection for sensitive operations

### 3. **Front-Running Protection**
- Use appropriate slippage tolerance
- Consider using private mempools for large swaps (future enhancement)

### 4. **API Security**
- No API key required for basic usage
- Rate limiting handled by KyberSwap
- Consider adding `X-Client-Id` header for analytics

## 🎨 UI/UX Mockup

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ ← Swap Tokens β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β”‚
β”‚ From β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ ETH β–Ό β”‚ 1.0 [MAX] β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ Balance: 2.5 ETH β”‚
β”‚ β”‚
β”‚ ↓↑ β”‚
β”‚ β”‚
β”‚ To β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ USDC β–Ό β”‚ ~1,668.50 β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ Balance: 0 USDC β”‚
β”‚ β”‚
β”‚ ───────────────────────────────── β”‚
β”‚ β”‚
β”‚ Rate: 1 ETH = 1,668.50 USDC β”‚
β”‚ Price Impact: 0.12% β”‚
β”‚ Gas Fee: ~$0.50 β”‚
β”‚ Slippage: 0.5% [βš™οΈ] β”‚
β”‚ β”‚
β”‚ Route: Uniswap V3 (100%) β”‚
β”‚ β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ Review Swap β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

## πŸ“š Resources

- **KyberSwap Docs**: https://docs.kyberswap.com/
- **API Specification**: https://docs.kyberswap.com/kyberswap-solutions/kyberswap-aggregator/aggregator-api-specification/evm-swaps
- **Demo Implementation**: https://github.com/KyberNetwork/ks-aggregator-api-demo
- **Supported Networks**: https://docs.kyberswap.com/getting-started/supported-exchanges-and-networks

## βœ… Success Criteria

- [ ] Users can swap any supported token pair on their selected network
- [ ] Swap transactions require passkey authentication (maintaining EthAura security model)
- [ ] UI shows accurate pricing, gas estimates, and route information
- [ ] Slippage protection prevents unexpected losses
- [ ] Error messages are clear and actionable
- [ ] Swap history appears in transaction list
- [ ] Works with both deployed and counterfactual accounts

## πŸš€ Future Enhancements

- [ ] **Limit Orders**: Use KyberSwap Limit Order API
- [ ] **Cross-Chain Swaps**: Integrate bridge aggregators
- [ ] **Swap Routing Comparison**: Show multiple route options
- [ ] **Price Alerts**: Notify when target price is reached
- [ ] **Recurring Swaps**: DCA (Dollar Cost Averaging) automation
- [ ] **MEV Protection**: Integrate Flashbots or private RPC

## 🏷️ Labels

`enhancement` `feature` `swap` `defi` `kyberswap` `high-priority`

---

**Estimated Effort**: 2-3 weeks
**Priority**: High
**Dependencies**: None (uses existing P256Account infrastructure)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.