[Ethereum] Transfer ERC20 token from a smart-contract

erc-20solidity

I am facing an issue and I can't figure what's going wrong.

It is a very simple scenario:

A smart-contract, that implements ERC20 and ERC20Mintable from OpenZeppelin.

pragma solidity ^0.5.0;

import "./openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "./openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol";

contract MyToken is ERC20, ERC20Mintable {}

Another smart-contract that received some MyToken.

pragma solidity ^0.5.0;

import "./MyToken.sol";

contract TokenInteraction {

    address public tokenAddress;

    constructor(address _tokenAdd) public {
        tokenAddress = _tokenAdd;
    }

    function transferToken(address to) public {
        MyToken myToken = MyToken(tokenAddress);
        myToken.transfer(to, 1);
    }

}

I checked that TokenInteraction has more than one token, but when I call transferToken the transaction revert.

I don't understand what's happening.

Many thanks for you help!

EDIT :
Concerning the deployment and the testing methodology, I use Remix IDE on localhost and I deploy on Ganache running locally. To test it, I just mint a token to TokenInteraction and then try to call transferToken to another address

Best Answer

I successfully transferred token with your code. I guess the reason why you encountered problem was a mis-setup at deployment. Please try out the following procedure with Remix IDE to see if it works for you.

Deployment

  1. Deploy MyToken contract
  2. Copy the address of the deployed contract
  3. Deploy TokenInteraction and pass the address copied at step 2 to the constructor.
  4. Once the TokenInteraction contract is deployed, check if tokenAddress matches the address got from step 2

Mint tokens to TokenInteraction contract

  1. Copy the address of the deployed TokenInteraction contract.
  2. Select a minter account (by default, the creator of the MyToken contract) and call the mint function with the address from the previous step as well as the amount.
  3. Check with the balanceOf function to verify everything is good.

Transfer tokens to another address

Pass the recipient address when calling transferToken of TokenInteraction contract.

Verify Results

Check the balance of the recipient and that of the TokenInteraction contract.

Related Topic