0

I am new to Solidity programming and trying to use ERC20 openzeppelin contract to send tokens using transfer function. Following example code:

Token.sol file

pragma solidity >=0.8.7;

import 'https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol';

contract Token is ERC20 {
    constructor(string memory name, string memory symbol) ERC20(name, symbol) {}
}

TransferToken.sol file

pragma solidity >=0.8.7;

import './6_Token.sol';

contract TransferToken {

  function transfer() external {
    Token token = Token(msg.sender);
    token.transfer(0x617F2E2fD72FD9D5503197092aC168c91465E7f2, 1 ether);
  }  
}

When I click on transfer button in Remix, below error throws.

transact to TransferToken.transfer pending ... transact to TransferToken.transfer errored: VM error: revert. revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information.

I am able to make transfer without using ERC20 implementation such as recipient.transfer(1 ether) works fine after depositing ether into calling smart contract. But the same does not work when using Token.transfer from openzeppelin ERC20.

Please help to understand what could be the problem.

Thanks!

1 Answer 1

0

you can not mint ERC20 token in your account first mint token in your account after you can transfer to anyone that token.

Try this :

Token.sol

pragma solidity >=0.8.7;

import 'https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol';

contract Token is ERC20 {
    constructor(string memory name, string memory symbol , uint256 supply) ERC20(name, symbol) {
            _mint(msg.sender,supply * 10 ** decimals())
}
}

1
  • Hi Akshay I have added the above suggested minting function and deployed with supply = 50 tokens. Deployment is successful and i have checked the balanceOf msg.sender, it shows me the correct balance in wei (500000.....) units. When I transfer using TransferToken.sol, it still throws same error. Am I creating the token object in right way? function transfer() external payable { Token token = Token(msg.sender); token.transfer(0x617F2E2fD72FD9D5503197092aC168c91465E7f2, 1000000000000); }
    – Khalid
    Feb 18, 2022 at 15:04

Your Answer

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

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