A comprehensive tutorial demonstrating how to use the Coinbase Developer Platform (CDP) SDK to perform token swaps on the Base network. This project shows both the recommended all-in-one approach and the advanced create-then-execute pattern for token swapping.
- Token Swapping: Swap between ERC20 tokens on Base mainnet
- Dual Approaches: All-in-one pattern (recommended) and create-then-execute pattern
- Allowance Management: Automatic token allowance handling for ERC20 tokens
- Slippage Protection: Configurable slippage tolerance for swaps
- Transaction Monitoring: Real-time transaction confirmation tracking
- Comprehensive Examples: WETH to USDC swap demonstration
- TypeScript: Full TypeScript implementation for type safety
- Node.js: JavaScript runtime environment
- TypeScript: Type-safe JavaScript superset
- Coinbase CDP SDK: For wallet management and swap operations
- Viem: Ethereum interactions and transaction handling
- Base Network: Layer 2 network for efficient and low-cost swaps
- Node.js (v16 or later)
- npm or yarn package manager
- Coinbase Developer Platform (CDP) API credentials
- Base mainnet tokens (WETH for the demo)
- Understanding of ERC20 token mechanics
# Clone the repository
git clone https://github.com/HeimLabs/coinbase-cdp-demos.git
cd 10-CDP-SwapAPI-Demo
# Install dependencies
npm installCreate a .env file in the root directory:
# Copy the example environment file
cp .env.example .envEdit the .env file and add your CDP credentials:
# Coinbase Developer Platform API Keys
CDP_API_KEY_ID=your_cdp_api_key_id
CDP_API_KEY_SECRET=your_cdp_api_key_secret
CDP_WALLET_SECRET=your_cdp_wallet_secretBefore running the demo, ensure your wallet has WETH tokens:
# You'll need WETH tokens on Base mainnet
# You can wrap ETH to WETH or get WETH from a DEX# Build the TypeScript code
npm run build
# Run the swap demo
npm startThe demo demonstrates token swapping with these key steps:
- Account Setup: Create or retrieve a CDP wallet account
- Token Allowance: Check and approve token allowances for Permit2
- Swap Execution: Execute the token swap using one of two approaches
- Transaction Monitoring: Monitor and confirm the swap transaction
The demo uses these Base mainnet tokens:
const TOKENS = {
WETH: {
address: "0x4200000000000000000000000000000000000006",
symbol: "WETH",
decimals: 18
},
USDC: {
address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
symbol: "USDC",
decimals: 6
}
};The recommended approach for most use cases:
const result = await account.swap({
network: "base",
fromToken: fromToken.address,
toToken: toToken.address,
fromAmount: parseUnits("0.0004", 18),
slippageBps: 100, // 1% slippage tolerance
});Advantages:
- Single function call
- Automatic quote creation and execution
- Built-in error handling
- Best for 90% of use cases
For scenarios requiring more control:
// Step 1: Create swap quote
const swapQuote = await account.quoteSwap({
network: "base",
fromToken: fromToken.address,
toToken: toToken.address,
fromAmount: parseUnits("0.0004", 18),
slippageBps: 100,
});
// Step 2: Inspect quote details
console.log(`Expected to receive: ${formatUnits(swapQuote.toAmount, 6)} USDC`);
// Step 3: Execute swap
const result = await account.swap({ swapQuote });Advantages:
- More control over the swap process
- Ability to inspect quote details before execution
- Better for complex scenarios requiring validation
When you run the demo, you'll see output like:
🚀 CDP SDK Token Swap Tutorial - All-in-One Pattern
📍 Network: base
⚠️ Make sure you have WETH tokens available for swapping!
✅ Using account: 0x123...abc
🔍 Checking WETH allowance to Permit2 contract...
Current allowance: 0.0004 WETH
✅ Token allowance sufficient: 0.0004 WETH
💱 Planning to swap 0.0004 WETH for USDC
📚 APPROACH 1: All-in-one Pattern (Recommended)
This approach handles everything in a single call.
🔄 Creating and executing swap in one call...
✅ Swap submitted successfully!
📋 Transaction hash: 0xabc...def
⏳ Waiting for confirmation...
🎉 Swap Transaction Confirmed!
📦 Block number: 12345678
⛽ Gas used: 150000
📊 Status: Success ✅
🔍 View on Basescan: https://basescan.org/tx/0xabc...def
CDP_API_KEY_ID: Your CDP API key identifierCDP_API_KEY_SECRET: Your CDP API key secretCDP_WALLET_SECRET: Your CDP wallet secret for encryption
You can customize the swap by modifying these parameters:
// Token amount (in string format)
const swapAmount = "0.0004"; // 0.0004 WETH
// Slippage tolerance (in basis points)
const slippageBps = 100; // 1% slippage
// Network (currently supports Base mainnet)
const NETWORK = "base";To add support for other tokens:
const TOKENS = {
// Add new tokens here
DAI: {
address: "0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb",
symbol: "DAI",
decimals: 18,
isNativeAsset: false
},
// ... existing tokens
};- Slippage Protection: Configurable slippage tolerance prevents unexpected losses
- Allowance Management: Secure token allowance handling through Permit2
- Transaction Verification: All transactions are verified on-chain
- Error Handling: Comprehensive error handling for various failure scenarios
The demo automatically handles ERC20 token allowances:
// Check current allowance
const currentAllowance = await getAllowance(
ownerAddress,
tokenAddress,
tokenSymbol
);
// Approve tokens if needed
if (currentAllowance < fromAmount) {
await approveTokenAllowance(
ownerAddress,
tokenAddress,
PERMIT2_ADDRESS,
fromAmount
);
}Real-time transaction confirmation:
const receipt = await publicClient.waitForTransactionReceipt({
hash: result.transactionHash,
});
console.log(`📦 Block number: ${receipt.blockNumber}`);
console.log(`⛽ Gas used: ${receipt.gasUsed}`);
console.log(`📊 Status: ${receipt.status === 'success' ? 'Success ✅' : 'Failed ❌'}`);- Portfolio Rebalancing: Automatically rebalance token portfolios
- Trading Bots: Implement automated trading strategies
- DeFi Integration: Integrate swaps into DeFi applications
- Cross-Chain Bridging: Prepare tokens for cross-chain transfers
- Yield Optimization: Swap to higher-yield tokens
npm run build: Build TypeScript to JavaScriptnpm start: Run the swap demonpm run transfer: Run token transfer demo (if available)
You can test various scenarios by modifying the code:
// Test different amounts
const swapAmount = "0.001"; // Try different amounts
// Test different slippage tolerances
slippageBps: 50, // 0.5% slippage (tighter)
slippageBps: 300, // 3% slippage (looser)
// Test different token pairs
const fromToken = TOKENS.USDC;
const toToken = TOKENS.WETH;The demo includes comprehensive error handling:
try {
const result = await account.swap({...});
} catch (error) {
if (error.message?.includes("Insufficient liquidity")) {
console.log("❌ Swap failed: Insufficient liquidity");
console.log("💡 Try reducing the swap amount or using a different token pair");
} else {
throw error;
}
}For production use, consider:
- Slippage Management: Implement dynamic slippage based on market conditions
- MEV Protection: Use MEV-protected RPC endpoints
- Rate Limiting: Implement rate limiting for API calls
- Error Recovery: Implement retry logic for failed transactions
- Gas Optimization: Monitor and optimize gas usage
- Multi-DEX Support: Compare quotes from multiple DEXs
- Insufficient Allowance: Ensure token allowances are properly set
- Insufficient Liquidity: Try smaller amounts or different token pairs
- High Slippage: Increase slippage tolerance or reduce swap amount
- Network Issues: Check Base network status and RPC connectivity
- Check token balances before swapping
- Monitor gas prices and network congestion
- Verify token contract addresses
- Test with small amounts first
- CDP SDK Documentation
- Base Network Documentation
- Viem Documentation
- Permit2 Documentation
- ERC20 Token Standard
- Never commit your
.envfile or expose private keys - Use mainnet only for production swaps
- Always verify transaction details before execution
- Monitor slippage and MEV protection
- Keep API keys secure and rotate regularly
This project is licensed under the ISC License.
Disclaimer: This project is for demonstration purposes. For production use, additional security measures, monitoring, and testing should be implemented. Always test thoroughly on testnets before using mainnet.
Built with ❤️ using Coinbase Developer Platform and Viem.