Basic Token Swap
Overview
Prerequisites
Smart Contract Integration
Simple Swap Contract
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/ICrossChainAggregator.sol";
contract BasicSwapExample {
using SafeERC20 for IERC20;
ICrossChainAggregator public immutable aggregator;
constructor(address _aggregator) {
aggregator = ICrossChainAggregator(_aggregator);
}
function swapTokens(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 amountOutMin,
address recipient
) external returns (uint256 amountOut) {
// Transfer input tokens from user
IERC20(tokenIn).safeTransferFrom(msg.sender, address(this), amountIn);
// Approve aggregator to spend tokens
IERC20(tokenIn).safeApprove(address(aggregator), amountIn);
// Get quote for the swap
uint256 expectedOut = aggregator.getAmountOut(
amountIn,
tokenIn,
tokenOut
);
require(expectedOut >= amountOutMin, "Insufficient output amount");
// Execute the swap
amountOut = aggregator.swapExactTokensForTokens(
amountIn,
amountOutMin,
tokenIn,
tokenOut,
recipient
);
return amountOut;
}
}Frontend Integration
Using ethers.js
React Component Example
CLI Example
Using Hardhat Script
Price Impact and Slippage
Understanding Slippage
Price Impact Calculation
Error Handling
Common Errors and Solutions
Gas Optimization
Batch Operations
Gas Estimation
Best Practices
1. Always Check Allowances
2. Implement Proper Slippage Protection
3. Use Deadline for Time Protection
4. Monitor Transaction Status
Testing
Unit Tests
Resources
Last updated