0

ERROR MESSAGE: Gas estimation failed Close Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending? Internal JSON-RPC error. { "code": -32000, "message": "execution reverted" }

Hi. I'm having an issue with swapping executing a basic uniswap swap smart contract. I actually copied the code directly from a tutorial and am still getting this issue when trying to execute on remix. I successfully compile and deploy the contract (on Polygon, using the UniswapV2Router02 contract address from polygonscan and the correct WETH address for polygon, but whenever I try to execute the swap function the above error ALWAYS arises. I execute it with high gas always, and have thought the problem many times but have no idea what the issue is.

If someone could assist me in successfully executing this contract I'd be highly appreciative!

This is my code:

pragma solidity ^0.6.12;

import { IERC20 } from "./Interfaces.sol";
import "https://github.com/Uniswap/v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router02.sol";

contract UniswapSwap {
    address private constant UNISWAP_V2_ROUTER = 0xa5E0829CaCEd8fFDD4De3c43696c57F7D7A678ff;
    address private constant WETH = 0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619;


    function swap(address _token0, address _token1, uint256 _amountIn, uint256 _amountOutMin, address _to) external {
        IERC20(_token0).transferFrom(msg.sender, address(this), _amountIn);
        IERC20(_token0).approve(UNISWAP_V2_ROUTER, _amountIn);

        address[] memory path;
        path = new address[](2);
        path[0] = _token0;
        path[1] = _token1;

        IUniswapV2Router02(UNISWAP_V2_ROUTER).swapExactTokensForTokens(
            _amountIn,
            _amountOutMin,
            path,
            _to,
            block.timestamp
        );
    }
} 

[![error message picture][1]][1]

1 Answer 1

0

Before you called the function swap(...), you must approve the contract to access your funds. Consequently, the user have to give permission to the your smart contract to access at funds and only then you'll call swap(...) function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.