Basic Token Swap

This example demonstrates how to perform a basic token swap using the IU2U Protocol's DEX aggregation capabilities.

Overview

A basic token swap allows users to exchange one token for another through the best available route across multiple DEX protocols, all in a single transaction.

Prerequisites

  • Wallet with tokens to swap

  • Sufficient gas for transaction execution

  • Basic understanding of ERC20 tokens

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

Run the script:

Price Impact and Slippage

Understanding Slippage

Slippage is the difference between expected and actual execution price:

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