3

I would like to allow a deployed smartContract1 to approve its ERC20 tokens (the tokens held in the contract) to smartContract2 such that smartContract2 can then spend them. Is this only possible if smartContract1 implements some approval function, or can I call approve() on smartContract1 somehow? To rephrase; can a smart contract grant approval over its tokens or is this only possible for EOAs?

Thank you and let me know if this is unclear!

1 Answer 1

2

Yes, a smart contract can approve so another smart contract to spend its tokens.

This can be done with the approve method of the ERC20 token: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol#L136

Your contract cannot execute by itself, hence, you will need to write a function in the contract that is able to send the approval request to the ERC20 token so another contract or EOA can spend it.

For example:

// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

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

contract Contract {

    IERC20 public token;
    address public owner;

    modifier onlyOwner() {
        require(owner == msg.sender, "Not owner");
        _;
    }

    constructor(IERC20 _token) {
        token = _token;
        owner = msg.sender;
    }

    function approve(address spender, uint256 amount) external onlyOwner {
        token.approve(spender, amount);
    }

    // Other important functions.

}

This contract has the logic to approve an address (whether it's from a contract or any EOA address, no difference) to spend its tokens. Notice that it's important that only the owner of the contract can call this function.

If we send some tokens to the address of this smart contract, then it has some tokens that it can approve another contract or EOA to spend.

In the ECR20 base implementation, notice how the approve function gets the sender, which will be this contract's address, and approves the spender to spend a certain amount of its tokens.

enter image description here

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.