UniswapV2

DeeLMind小于 1 分钟

UniswapV2

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";

contract UniswapV2Example {
    IUniswapV2Router02 public uniswapRouter;
    address public owner;

    constructor(address _router) {
        uniswapRouter = IUniswapV2Router02(_router);
        owner = msg.sender;
    }

    // 用户通过此函数交换代币
    function swapTokensForTokens(
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 amountOutMin,
        address to,
        uint256 deadline
    ) external {
        // 允许合约转移用户的代币
        IERC20(tokenIn).transferFrom(msg.sender, address(this), amountIn);
        IERC20(tokenIn).approve(address(uniswapRouter), amountIn);

        // 进行代币交换
        address;
        path[0] = tokenIn;
        path[1] = tokenOut;

        uniswapRouter.swapExactTokensForTokens(
            amountIn,
            amountOutMin,
            path,
            to,
            deadline
        );
    }

    // 提取合约中的 ERC20 代币
    function withdrawToken(address token, uint256 amount) external {
        require(msg.sender == owner, "Only owner can withdraw");
        IERC20(token).transfer(owner, amount);
    }

    // 提取合约中的 ETH
    function withdrawETH(uint256 amount) external {
        require(msg.sender == owner, "Only owner can withdraw");
        payable(owner).transfer(amount);
    }

    // 接收 ETH
    receive() external payable {}
}
上次编辑于:
贡献者: DeeLMind