如何从solidity智能合约中调用UniswapV2 Router addLiquidityETH函数?

问题描述 投票:0回答:1

我正在尝试通过 Solidity 智能合约在 Uniswap v2 路由器中添加流动性,但即使已经给予了津贴,它似乎也失败了。

pragma solidity ^0.8.0;

import "./IUniswapV2Router01.sol";
import "./IERC20.sol"; // Import ERC20 interface if needed

contract MyContract {
    IUniswapV2Router01 public uniswapRouter;
    address public tokenAddress;
    
    constructor(address _router, address _tokenAddress) {
        uniswapRouter = IUniswapV2Router01(_router);
        tokenAddress = _tokenAddress;
    }
    
    function addLiquidityETH(uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, uint deadline) external payable {
        // Approve the router to spend the token on behalf of this contract
        IERC20 token = IERC20(tokenAddress);
        token.approve(address(uniswapRouter), amountTokenDesired);
        
        // Call addLiquidityETH function
        uniswapRouter.addLiquidityETH{value: msg.value}(
            tokenAddress,
            amountTokenDesired,
            amountTokenMin,
            amountETHMin,
            address(this),
            deadline
        );
    }
}

有人可以解释一下我犯了什么错误吗?或者可以帮助我使用实际的 Solidity 代码来调用 uniswapv2router 中的 addLiquidityETH 函数。

ethereum blockchain solidity smartcontracts uniswap
1个回答
0
投票

在向 Uniswap 池添加流动性之前,必须首先将要作为流动性添加的代币发送到处理流动性添加的合约。这意味着您必须调用

transferFrom
或为了更好的错误处理调用
safeTransferFrom

Openzeppelin 有 SafeERC20。在您的合同中实现这一点:

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

// inside contract
IERC20 token1 = IERC20(tokenAddress1);
IERC20 token2 = IERC20(tokenAddress2);

token1.safeTransferFrom(msg.sender, address(this), amountOfToken1);
token2.safeTransferFrom(msg.sender, address(this), amountOfToken2);
© www.soinside.com 2019 - 2024. All rights reserved.