Why am I getting this error Error: Transaction reverted without a reason string. When trying to swap tokens on uniswap?

Why am I getting this error Error: Transaction reverted without a reason string. When trying to swap tokens on uniswap?

我正在尝试在 uniswap unsing hardhat 的主网分叉上交换代币,但出现此错误:Error: Transaction reverted without a reason string。我真的不知道为什么。

这是我的交换函数:

    function swap(address router, address _tokenIn, address _tokenOut, uint _amount) public {
        IERC20(router).approve(router, _amount);
        address[] memory path;
        path = new address[](2);
        path[0] = _tokenIn;
        path[1] = _tokenOut;
        uint deadline = block.timestamp + 300;  
        IUniswapV2Router(router).swapExactTokensForTokens(_amount, 1, path, address(this), deadline);  
}

这是一个简单的功能,应该可以使用。我是这样称呼它的:

await arb.swap(
    uniAddress,
    wethAddress,
    daiAddress,
    ethers.utils.parseEther('0.5')
);

感谢解答!

另外,这里是我打电话的地址,只是为了验证它们是否正确,但我很确定它们是:

const wethAddress = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2';
const daiAddress = '0x6B175474E89094C44Da98b954EedeAC495271d0F';
const uniAddress = '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D';

Weth与其他令牌不同,您不能使用swapTokensForTokens。我们必须使用 swapEthForTokens 函数来代替,并且您必须单独声明数据选项。

所以在你的情况下我们需要做:

实体代码:

function swapEth(address router, address _tokenIn, address _tokenOut, uint _amount) public {
    IERC20(router).approve(router, _amount);
    address[] memory path;
    path = new address[](2);
    path[0] = _tokenIn;
    path[1] = _tokenOut;
    uint deadline = block.timestamp + 300;
    IUniswapV2Router(router). swapExactETHForTokens(... parameters);  
}

JS代码

const dataOption = { gasPrice: ethers.getDefaultProvider().getGasPrice(), gasLimit: 310000, value: ethers.utils.parseEther('0.5') }

await arb.swap(`enter code here`
    uniAddress,
    wethAddress,
    daiAddress,
    ethers.utils.parseEther('0.5'), // this parameter should be remove from the function declaration as well as in this Javascript
    dataOption
);