How to Uniswap swap tokens on the contract itself? ValueError: Gas estimation failed: 'execution reverted'

823 Views Asked by At

I'm looking to perform a Uniswap V3 swap from WMATIC to USDC. I have written and deployed my contact on the Polygon Mumbai Testnet using brownie-eth.

However, when calling the swap function on the contract, I get the following error:

ValueError: Gas estimation failed: 'execution reverted'. This transaction will likely revert. If you wish to broadcast, you must set the gas limit manually.

I'm unable to locate what exactly causes the swap to fail. There should more than enough WMATIC on the contract to execute the swap: https://mumbai.polygonscan.com/address/0xED85D87Ddf25036d8ea1F03005900f5524D65a26

pragma solidity ^0.8.0;

import {TokenSwap} from "./uniswap.sol";
import {ISwapRouter} from '../interfaces/ISwapRouter.sol';
import {TransferHelper} from '../contracts/uniswap/TransferHelper.sol';


contract swapTest {

    address public immutable tokenIn = 0xb685400156cF3CBE8725958DeAA61436727A30c3;
    address public immutable tokenOut = 0xe6b8a5CF854791412c1f6EFC7CAf629f5Df1c747;
    uint public immutable amount = 0.01*(1 ether);

    // Uniswap Config
    address private constant SWAP_ROUTER = 0xE592427A0AEce92De3Edee1F18E0157C05861564;
    ISwapRouter public immutable swapRouter = ISwapRouter(SWAP_ROUTER);
    uint24 public constant poolFee = 3000;

    // Safely transfer tokens
    function swapExactInputSingle() public returns (uint256 amountOut)
    {
        TransferHelper.safeApprove(tokenIn, SWAP_ROUTER, amount);
        ISwapRouter.ExactInputSingleParams memory params = ISwapRouter
            .ExactInputSingleParams({
                tokenIn: tokenIn,
                tokenOut: tokenOut,
                fee: 3000,
                recipient: address(this),
                deadline: block.timestamp,
                amountIn: amount,
                amountOutMinimum: 0,
                sqrtPriceLimitX96: 0
            });

        amountOut = swapRouter.exactInputSingle(params);
    }

} 

I would like the swap to take place on the contract itself (without having to approve the contract to spend the wallet balance, and have the swap be received by the sender.) So that's why I've changed recipient to be address(this), and not included a safeTransfer function.

0

There are 0 best solutions below