-1

I believe I have to use transferFrom function of ERC20. But I didn't get success. I also want to know will this approach show volume on chain for my contract address or I need to change the flow to EOA->smart contract->EOA.

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8;

interface IERC20 {
    function transfer(address _to, uint256 _value) external returns     (bool);
    function approve(address spender, uint256 value) external returns (bool);
    function transferFrom(address from, address to, uint256 value) external returns (bool);
    function balanceOf(address account) external view returns (uint256);
}

contract MyContract {

    function sendUSDT(address _from, address _to, uint256 _amount) external returns (bool) {
        IERC20 usdt = IERC20(address(0x2F7b97837F2D14bA2eD3a4B2282e259126A9b848));// mumbai testnet
        return usdt.transferFrom(_from, _to, _amount);
    }
    
    function approve(address spender, uint256 value) external returns(bool) {
        IERC20 usdt = IERC20(address(0x2F7b97837F2D14bA2eD3a4B2282e259126A9b848));
        return usdt.approve(spender, value);
    }

    function balanceOf(address account) external view returns (uint256){
        IERC20 usdt = IERC20(address(0x2F7b97837F2D14bA2eD3a4B2282e259126A9b848));
        return usdt.balanceOf(account);
    }

}
Petr Hejda
  • 40,554
  • 8
  • 72
  • 100

1 Answers1

0

I believe I have to use transferFrom function of ERC20

Correct. But before that, your contract needs to be approved by the user to spend their tokens. So it's a two-transaction process.

1st transaction: The user needs to execute the approve() function on the token contract directly - not through your contract. Passing your contract address (the spender) as the first argument, and the max amount they approve you to spend as the second argument.

2nd transaction: Only then you're able transferFrom() the user's tokens to another address through your contract.


The way your contract is written now, you're actually giving the spender approval to spend value of usdt tokens that are owned by your contract.

Petr Hejda
  • 40,554
  • 8
  • 72
  • 100