1

I want my contract (#1) to be able to approve another contract (#2) to transfer erc20 tokens from #1 to #2. Is this possible?

1 Answer 1

2

Yes, a contract can approve another contract to make transfer from its tokens.

contract A {
    ERC20 token;
    function approveAndCall(B recipient, uint amount) public {
        // Approve recipient to spend amount tokens
        require(token.approve(address(recipient), amount), "Approve has failed");

        // Call contract B to process payment
        require(recipient.processPayment(amount), "Payment failed");
    }
}

Recipient contract

contract B {
    ERC20 token;
    uint256 public constant ticketPrice = 10 ** 18; // 1 token assuming 18 decimals
    function processPayment(uint amount) public return bool {
        // Check price
        if (amount >= ticketPrice) {
            // Revert if tokens cannot be transfered
            require(token.transferFrom(msg.sender, address(this), ticketPrice), "Transfer failed");
            // Generate event when ticket is sold
            emit TicketSold(msg.sender, ticketPrice);
            return true;
        } else {
            // Return false to make caller detect a payment failure
            return false;
        }
    }
}

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.