我想通过流动性池的swap来直接交易代币,不知道为什么老是失败

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

interface IERC20 {
    function balanceOf(address account) external view returns (uint256);

    function transfer(address recipient, uint256 amount) external;

    function approve(address spender, uint256 amount) external returns (bool);

    function deposit() external payable;
}

interface IpancakePair {
    function swap(
        uint256 amount0Out,
        uint256 amount1Out,
        address to,
        bytes calldata data
    ) external;

    function getReserves()
        external
        view
        returns (
            uint112 reserve0,
            uint112 reserve1,
            uint32 blockTimestampLast
        );

    function token0() external view returns (address);

    function token1() external view returns (address);
}

contract Arbitrage {

    function performArbitrage(
        address[] memory pairAddresses,
        uint256 initialAmount,
        address initialInputToken
    ) external {
        require(pairAddresses.length > 0, "No pairs provided");

        uint256 amountIn = initialAmount;
        uint256 amountOutMin;
        address currentInputToken = initialInputToken;

        for (uint256 i = 0; i < pairAddresses.length; i++) {
            IpancakePair pair = IpancakePair(pairAddresses[i]);
            address token0 = pair.token0();
            address token1 = pair.token1();

            IERC20(currentInputToken).transfer(pairAddresses[i],amountIn);
            if (token0 == currentInputToken) {
                pair.swap(amountIn, 0, msg.sender, bytes(""));
                currentInputToken = token1;
            } else {
                pair.swap(0, amountIn,msg.sender, bytes(""));
                currentInputToken = token0;
            }

            (uint112 reserve0, uint112 reserve1, ) = pair.getReserves();
            amountOutMin = (currentInputToken == token0)
                ? (reserve1 * amountIn) / reserve0
                : (reserve0 * amountIn) / reserve1;

            amountIn = amountOutMin;
        }

    }
}

Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending? Returned error: {"jsonrpc":"2.0","error":"execution reverted","id":2434371941200578}

请先 登录 后评论

最佳答案 2023-10-26 09:42

可以用 foudry fork 主网部署合约,在本地调试。

另外,你的代码,第一个transfer的token 是那里来的?

请先 登录 后评论

其它 0 个回答

  • 2 关注
  • 0 收藏,1709 浏览
  • .1323232 提出于 2023-10-25 10:37