用swap进行购买币和 卖出币,现在的问题是购买可以成功,但卖出失败

就是想用uniswapV2Pair.swap方法把购买的币卖出去怎么做

用swap购买 `

    address pairAddr = getPairAddress(tokenAddress, routerAddress);//获取池子 pair地址
    transferTo(pairAddr, wbnbAmount); //转账给pair  wbnb

    IUniswapV2Pair uniswapV2Pair=IUniswapV2Pair(pairAddr);
    address token0= uniswapV2Pair.token0();
    (uint112 reserve0, uint112 reserve1,)=uniswapV2Pair.getReserves();
    (uint reserveInput, uint reserveOutput) = token0==WBNB_ADDRESS ? (reserve0, reserve1): (reserve1, reserve0);
    uint amountOut=IPancakeRouter02(PANCAKE_ROUTER_V2_ADDRESS).getAmountOut(wbnbAmount,reserveInput,reserveOutput);
    (uint amount0Out, uint amount1Out) = token0==WBNB_ADDRESS ? (uint(0),amountOut):(amountOut,uint(0));

    uniswapV2Pair.swap(amount0Out,amount1Out,to,new bytes(0));//swap转账币给自己
    `

============================================== 对应的卖出代码,失败,链都没上(remix),hash:0xf72c4bed3c98a108f311b8c6cadff713834cf7986b5fa9154903c8ce927c7881,代码如下

address pairAddr = getPairAddress(tokenAddress, routerAddress);

        IERC20 token = IERC20(tokenAddress);
        uint tokenBalance = token.balanceOf(address(this));
        if(token.allowance(address(this), routerAddress) < tokenBalance){
            require(token.approve(routerAddress, MAX_UINT),"FAIL TO APPROVE");
        }

        // from 部署的合约,to是池子地址
        //把tokenBalance的数量的tokenAddress代币转给pairAddr
        transferTo(fromAddress, pairAddr, tokenBalance);

      IUniswapV2Pair uniswapV2Pair=IUniswapV2Pair(pairAddr);
        address token0= uniswapV2Pair.token0();
        (uint112 reserve0, uint112 reserve1,)=uniswapV2Pair.getReserves();
        (uint reserveInput, uint reserveOutput) = token0!=WBNB_ADDRESS ? (reserve0, reserve1): (reserve1, reserve0);
        uint amountOut=IPancakeRouter02(PANCAKE_ROUTER_V2_ADDRESS).getAmountOut(amount,reserveInput,reserveOutput);
            (uint amount0Out, uint amount1Out) = token0!=WBNB_ADDRESS ? (uint(0),amountOut):(amountOut,uint(0));

        uniswapV2Pair.swap(amount0Out,amount1Out,toAddress,new bytes(0));

请大佬们指点指点

请先 登录 后评论

2 个回答

仗剑走天涯
请先 登录 后评论
zen
请先 登录 后评论
  • 1 关注
  • 1 收藏,2546 浏览
  • hunter666 提出于 2022-08-26 22:09