ERC-20 – Fixing approve() Not Working in Remix

erc-20remixsolidity

In Remix, I have a Depository smart contract that is supposed to escrow user funds. My first step is to call token.approve with the address of the deployed Depository and amount, but I'm not getting the expected behavior.

pragma solidity ^0.5.11;

import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.0/contracts/token/ERC20/ERC20.sol";

contract Token is ERC20 {}

contract Depository {
    function transferFrom(uint amount) external {
        Token token = Token(0xFab46E002BbF0b4509813474841E0716E6730136);
        token.transferFrom(msg.sender, address(this), amount);
    }
}

contract Owner {
    function transfer(uint amount) external {
        Token token = Token(0xFab46E002BbF0b4509813474841E0716E6730136);
        // 0xF5c73... is the address of the deployed Depository contract
        token.approve(0xF5c7313cB994A0F8cEee341dC61C15753F775Fcf, amount);

        // Now that Depository is approved to spend amount tokens, instruct it to transferFrom
        Depository depository = Depository(0xF5c7313cB994A0F8cEee341dC61C15753F775Fcf);
        depository.transferFrom(amount);

    }
}

Owner.transfer's token.approve doesn't seem to behave. I'm calling it from an address with 10000 ERC20 tokens and passing 50 as the amount argument. When I invoke transfer, two things happen:

  1. I get the alert: Gas estimated failed. Gas estimated errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending? The execution failed due to an exception. Reverted
  2. After clicking Send Transaction anyway, I'm presented with the following Metamask window, which isn't the expected approve transaction.

enter image description here

enter image description here

I'm new to Solidity, and pretty darn stumped. Where am I going wrong?

Best Answer

I'm calling it from an address with 10000 ERC20 tokens

You need to have the tokens in the Owner contract. As the owner contract is the one that is calling approve.

The failure is happening because there aren't enough ERC20 tokens in the Owner contract. Transfer 50 to that from your user wallet and then call the function.

Related Topic