1

We know openzeppelin has an interface named IERC20.sol, my doubt is related to interface. As this interface has functions like:

function transfer(address to, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);

My question is, is this interface usable because there are a contract named ERC20 and this contract has implementations of these functions? like this:

function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

If ERC20 would not have implementation of these function wouldn't IERC20 work? I saw IERC20 did not imported ERC20, so how it will make the connection? If we don't do IERC20(address_of_ERC20) then the interface won't work anymore??

1 Answer 1

1

IERC20 is an interface for ERC20.

It defines required functions, but it doesn't provide implementation. It makes sure that the ERC20 contract implements these functions.

You can use IERC20 to interact with any contract that follows the ERC20 standard.

Connection between IERC20 and ERC20 is not automatic.

You need to specify the address of the ERC20 contract when you use the IERC20 interface.

Example:

Deploy ERC20 contract, get its address: 0x1234... Use IERC20 interface in another contract, and provide ERC20 contract's address:

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract MyContract {
    IERC20 private _token;

    constructor(address tokenAddress) {
        _token = IERC20(tokenAddress);
    }

    function transferToken(address to, uint256 amount) public {
        _token.transfer(to, amount);
    }
}

Here, MyContract uses IERC20 to interact with the deployed ERC20 contract at the specified address. If ERC20 didn't implement IERC20 functions, it would simply fail.

Additionally, you can ensure your contract is IERC20 compatible by inheriting from the IERC20 interface as follow:

contract MyContract is IERC20

This ensures that your contract has implemented all the functions defined in the IERC20.

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.