Need to deposit all erc20tokens in my wallet into smart contract which I deployed


function approveOtherContract(IERC20 _token, address recipient) public returns(bool){
        return _token.approve(recipient, 1e18);
    }
    
    function tokenTransfer(address _token, uint _amount) public {
        //IERC20(_token).approve(_contract,_amount);
        IERC20(_token).transferFrom(msg.sender, address(this), _amount);
        newTokens.push(_token);
    }
    
    function getBalanceOfToken(address _address) public view returns (uint) {
        return IERC20(_address).balanceOf(address(this));
    }

I approved contract using function approveOtherContract ,but at time of tokentransfer it does not work and gives error - Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending?
execution reverted: ERC20: transfer amount exceeds allowance { "originalError": { "code": 3, "data": "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002845524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e6365000000000000000000000000000000000000000000000000", "message": "execution reverted: ERC20: transfer amount exceeds allowance" } }

You can't approve an external token using another contract. You must use the approve function directly on the token contract

This means that the current contract is approving the recipient, because the contract is the msg.sende

2 Likes

Thanks for your reply @FreezyEx.
Now I understand.
So we have to do it using web3(can I get example) or is there any way to do it using smart contract.
Thanks in advance.

2 Likes

Yes you can use web3 on a dapp, like pancake does, or simply go to the token contract and call approve there

1 Like

Got it @FreezyEx
Thanks again.

1 Like

Hey @FreezyEx
I did this using web3

const tokenContract  = new web3.eth.Contract(tokenAbi,tokenAddress)
const user = '0x7259901b0c2688c6B9a421e19eDA3f036E86FEa7'
tokenContract.methods.approve(address,'1000000000000').send({from : user},(err,txHash) => console.log('txHash:',txHash))

Then I tried to call this -

    function tokenTransfer(address _token, uint _amount) public {
        //IERC20(_token).approve(_contract,_amount);
        IERC20(_token).transferFrom(msg.sender, address(this), _amount);
        newTokens.push(_token);
    }

from smart contract still getting the same error.

Then I tried this on web3 -

tokenContract.methods.transferFrom(user,address,'1000').send({from : user},(err,txHash) => console.log('txHash:',txHash))

But for both txHash : undefined

Also triggered this from my smart contract -

    function getBalanceOfToken(address _address) public view returns (uint) {
        return IERC20(_address).balanceOf(address(this));
    }

ZERO balance