0

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

1 Answer 1

0

As only the owner of the tokens can approve the spending of their tokens, yes it should be Contract A that call the approveAndTransferFrom function, with the spender being the TokenTransferContract contract.

However it seems like a bad idea because it would results in the same result as if Contract A simply transferred the tokens directly to Contract B but with higher gas cost.

If your goal is do both operations in a single transaction, you might want to check out this thread: Is it possible to make approve and transferfrom in single transaction?

1
  • Yeah, I already referred that thread in my question.
    – ratib90486
    Commented Nov 14, 2023 at 12:30

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.