0

Hello all I've recently starting diving into solidity development and I'm having trouble with ERC20 token interactions.

What I want to accomplish is sending ERC20 tokens to a smart contract that I created.

pragma solidity ^0.5.0;

contract ERC20 {
    function totalSupply() public view returns (uint supply);
    function balanceOf(address _owner) public view returns (uint balance);
    function transfer(address _to, uint _value) public returns (bool success);
    function transferFrom(address _from, address _to, uint _value) public returns (bool success);
    function approve(address _spender, uint _value) public returns (bool success);
    function allowance(address _owner, address _spender) public view returns (uint remaining);
    function decimals() public view returns(uint digits);
    event Approval(address indexed _owner, address indexed _spender, uint _value);
}

contract MySmartContract {
    function approveDeposit(address tokenAddress) public {
        ERC20 token = ERC20(tokenAddress);
        token.approve(address(this), token.balanceOf(msg.sender));
    }

    function depositToken(address tokenAddress) public {
        ERC20 token = ERC20(tokenAddress);
        uint tokenAmount = token.balanceOf(msg.sender);
        token.transferFrom(msg.sender, address(this), tokenAmount);
    }
}

In my wallet I have BAT tokens. After calling the approveDeposit function with the BAT token address, I try calling depositToken but it returns an error.

What am I doing wrong?

0

In order for this to complete successfully when executed from a function in your contract:

token.transferFrom(msg.sender, address(this), tokenAmount);

You need to execute approve(yourContractAddress, tokenAmount) using the msg.sender account.


But when you do this from a function in your contract:

token.approve(address(this), token.balanceOf(msg.sender));

You are executing approve using your contract account, which means that you allow some other account to transfer tokens from your contract. Moreover, by passing this as the first parameter, that other account is your own contract. In other words, you are approving your contract to transfer tokens from itself, which is of course useless.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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