Feature: Token Swap Integration via KyberSwap Aggregator API
- 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
Assessment
This issue has not been assessed yet.