0

I've developed an ERC20 token using Solidity and have successfully tested its liquidity functions on Hardhat. The process completes successfully in the Hardhat environment, but when I attempt the same on the main network using the provider at https://base.blockpi.network/v1/rpc/02fd1c96271cc939f4b0bfdbc6add1f41b1235f1, my transactions revert every time.

I've tried adding multiple checks within the contract to diagnose and resolve the issue, but these haven't helped. Below are the relevant portions of my contract code along with the deployment and function call scripts. Any insights into why these reverts may be occurring or suggestions on potential fixes would be greatly appreciated. Contract Code:

contract Token is ERC20, Ownable {
    using SafeMath for uint256;

    IUniswapV2Router02 public immutable uniswapV2Router;
    address
public immutable uniswapV2Router;
address public uniswapV2Pair;
mapping(address => bool) private _automatedMarketMakerPairs;
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);

constructor(string memory name, string memory symbol, uint256 initialSupply) ERC20(name, symbol) Ownable() {
    _transferOwnership(msg.sender);
    uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
    _approve(address(this), address(uniswapV2Router), type(uint256).max);
    _mint(address(this), initialSupply);
}

receive() external payable {}

function addLiquidity(uint tokenAmount, uint ethAmount) public onlyOwner {
    require(address(this).balance >= ethAmount, "Insufficient ETH balance");
    if (uniswapV2Pair == address(0)) {
        uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH());
        if (uniswapV2Pair == address(0)) {
            revert PairCreationFailed();
        }
        _setAutomatedMarketMakerPair(uniswapV2Pair, true);
    }
    bool isApproved = _approve(address(this), address(uniswapV2Router), tokenAmount);
    if (!isApproved) {
        revert ApprovalFailed(address(this), address(uniswapV2Router));
    }
    (uint amountToken, uint amountETH, uint liquidity) = uniswapV2Router.addLiquidityETH{value: ethAmount}(
        address(this),
        tokenAmount,
        0, // Minimum tokens expected
        0, // Minimum ETH expected
        owner(),
        block.timestamp
    );
    require(amountToken > 0 && amountETH > 0 && liquidity > 0, "Liquidity addition failed");
}

Deployment and Function Call Script:

try {
    const provider = getBatchProviderBase();
    const signer = new ethers.Wallet(privateKey, provider);
    const tokenContract = new Contract(contractAddress, abi, signer);

    const tokenAmountFormatted = ethers.utils.parseUnits(tokenAmount, 18); // Formatting the token amount
    const ethAmountFormatted = ethers.utils.parseEther(ethAmount); // Formatting the ETH amount




    const transaction = await tokenContract.addLiquidity(
      tokenAmountFormatted, // Token amount in smallest units
 
      ethAmountFormatted,
      {
        gasLimit: BigNumber.from("1000000"),
 gasPrice: await getAppropriateMarketGasPrice(provider),
      }
    );


    await transaction.wait();
    console.log('Liquidity added successfully');
  } catch (error) {
    console.error(`Failed to add liquidity: ${error}`);
    throw error;
  }

Hardhat working script:

import { BigNumber } from "ethers";

const hre = require("hardhat");

async function main() {
  const [owner] = await hre.ethers.getSigners();
  const tokenAddress = "0x5FbDB2315678afecb367f032d93F642f64180aa3";
  const Token = await hre.ethers.getContractFactory("Token");
  const token = Token.attach(tokenAddress);

  const tokenAmount = hre.ethers.utils.parseUnits("1000000", 18); // Token amount in the smallest unit
  const ethAmount = hre.ethers.utils.parseEther("0.000002"); // ETH amount in Wei


  try {
    const transactionResponse = await token.addLiquidity(tokenAmount, ethAmount, {

 maxPriorityFeePerGas,
      gasLimit: BigNumber.from("1000000"),
      
    });
    await transactionResponse.wait();
    console.log("Liquidity added!");
  } catch (error) {
    console.error("Failed to add liquidity:", error);
  }
}

main().catch((error) => {
  console.error("Error running script:", error);
  process.exitCode = 1;
});
1
  • Can you check that you deployed the contract on etherum (check on etherscan) and that it has enough ETH?
    – 0xSanson
    Commented May 14 at 17:14

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.