0

I'm struggling with transferring my own ERC20 Token.

I got following code:

contract AccountingToken is ERC20, ERC20Detailed {
constructor () public ERC20Detailed("AccountingToken", "MAC", 18) {
        _mint(msg.sender, 10000 * (10 ** uint256(decimals())));
    }
}

contract Accounting{
AccountingToken instance=AccountingToken(0x000...);

function get_balance()public view returns(uint){
        uint balance;
        balance=instance.balanceOf(msg.sender);
        return balance;
    }
function transfer_to_contract(uint tokens)public{
        address receiver=0x..receiver_address;
        instance.transfer(receiver,tokens);
}
}

Running the get_balance() function gives me the correct amount back.

But running the transfer() function always ends in a JSON-RPC error.

What am I doing wrong?

Thanks!

2
  • What parameters are you sending to transfer()? What's the error you get?
    – user19510
    Commented Sep 19, 2019 at 16:34
  • Found the problem... Tried to send money from a contract that hadn't got the amount of token. So it was a careless mistake...
    – Moodai
    Commented Sep 20, 2019 at 9:36

2 Answers 2

1

Found the problem... Tried to send money from a contract that hadn't got the amount of token. So it was a careless mistake...

0
1

The way your function works:

function transfer_to_contract(uint tokens)public{
        address receiver=0x..receiver_address;
        instance.transfer(receiver,tokens);
}

Is that under the hood the instance.transfer is calling one other function:

_transfer(msg.sender, recipient, amount);

And since you called transfer from your contract the msg.sender is not the address called transfer_to_contract but the address of your contract. So basically you are trying to send some tokens from your contract to your address. That is way it is failing.

In order to do what you want you have to use the function transferFrom(address sender, address recipient, uint256 amount) instead of transfer(address recipient, uint256 amount).

Then it would looks like this:

function transfer_to_contract(uint tokens)public{
        address receiver=0x..receiver_address;
        instance.transferFrom(msg.sender, receiver, tokens);
}

Note: in order the transfer to pass the sender first must have approve the amount of tokens he wnat to send via approve(address spender, uint256 amount) and the spender must be your contract address

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.