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
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;
}
}
}