Home > Blockchain >  Creation of CustomToken errored: VM error: revert
Creation of CustomToken errored: VM error: revert

Time:12-11

I new to solidity so could you guys please help me thanks? I tried to deploy the contract will ETH Value but always got the error "The transaction has been reverted to the initial state. The called function should be payable if you send value and the value you send should be less than your current balance.". Is there any way to fix this?

// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract CustomToken is ERC20 {
    constructor(string memory name, string memory symbol) ERC20(name, symbol){
        _mint(msg.sender, 1000000 * 10 ** 18);
    }
}

contract Uniswap {
    // Custom tokens to be initialiazed
    string[] public tokens = ["CoinA", "CoinB", "CoinC"];

    // map to maintain the tokens and its instances
    mapping(string => ERC20) public tokenInstanceMap;

    // 1 CoinA/CoinB/COinC = 0.0001 eth
    uint256 ethValue = 100000000000000;

    // 0.0001 eth = 1 CoinA/CoinB/CoinC
    // 1 CoinA/CoinB/CoinC = 1 CoinA/CoinB/CoinC

    constructor() {
        for (uint i=0; i<tokens.length; i  ) {
            CustomToken token = new CustomToken(tokens[i], tokens[i]);
            tokenInstanceMap[tokens[i]] = token;
        }
    }

    function getBalance(string memory tokenName, address _address) public view returns (uint256) {
        return tokenInstanceMap[tokenName].balanceOf(_address);
    }

    function getTotalSupply(string memory tokenName) public view returns (uint256) {
        return tokenInstanceMap[tokenName].totalSupply();
    }

    function getName(string memory tokenName) public view returns (string memory) {
        return tokenInstanceMap[tokenName].name();
    }

    function getTokenAddress(string memory tokenName) public view returns (address) {
        return address(tokenInstanceMap[tokenName]);
    }

    function getEthBalance() public view returns (uint256) {
        return address(this).balance;
    }

    function swapEthToToken(string memory tokenName) public payable returns (uint256) {
        uint256 inputValue = msg.value;
        uint256 outputValue = (inputValue / ethValue) * 10 ** 18; // Convert to 18 decimal places
        require(tokenInstanceMap[tokenName].transfer(msg.sender, outputValue));
        return outputValue;
    }

    

    
}

I try with 0 ETH and it worked fine! (https://i.stack.imgur.com/UtLNt.png) However, with 1 ETH and it got error message (https://i.stack.imgur.com/MsjE0.png)

CodePudding user response:

A function needs to use the payable modifier in order to accept ETH.

When you're deploying a contract, it executes the constructor.

constructor(string memory name, string memory symbol) ERC20(name, symbol) payable {
    _mint(msg.sender, 1000000 * 10 ** 18);
}
  • Related