I'm trying to perform approve and transfer under one tx but I don't understand which contract should be calling the approveAndTransferFrom
function? Say contract A is trying to transfer tokens to contract B, so should contract A call the function? I also referred to this but it doesn't say also.
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract TokenTransferContract {
// Reference to the ERC-20 token contract
IERC20 private token;
// Event to log successful transfer
event TransferApprovedAndExecuted(address indexed from, address indexed to, uint256 amount);
// Constructor to set the ERC-20 token contract address
constructor(address _tokenAddress) {
token = IERC20(_tokenAddress);
}
// Function to approve and transfer tokens in a single transaction
function approveAndTransferFrom(address _spender, address _to, uint256 _amount) external {
// Approve the spender to spend tokens on behalf of the contract
token.approve(_spender, _amount);
// Transfer tokens from the contract to the specified address
token.transferFrom(address(this), _to, _amount);
// Emit an event to log the successful transfer
emit TransferApprovedAndExecuted(address(this), _to, _amount);
}
}