0

I'm trying to transfer USDT tokens from my metamask account to another address(which is variable in smart contract) through method call.

if I use transfer method, I'm getting not enough balance(because it refers to balance of smart contract not my metamask wallet). If I use transferFrom I'm getting error saying transfer amount exceeds allowance. So I'm trying to understand what I'm doing wrong

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

using SafeERC20 for IERC20;


contract Shop{
address usdtContractAddress;
address usdtWalletOfShop;
function approve(uint128 amount) public  {
            IERC20(usdtContractAddress).approve(address(this), amount);
    }

    function order(uint128 amount) public {
        // IERC20((usdtContractAddress)).transfer(usdtWalletOfShop, amount);
        IERC20((usdtContractAddress)).transferFrom(msg.sender, usdtWalletOfShop, amount);
        usdtBalanceOfShop += amount;
        orderId += 1;
        emit Payment(msg.sender, amount, orderId);
    }

}

2 Answers 2

1

When using transferFrom, the address you are transferring from must first Approve some amount of spending. Because you are transferring on behalf of someone, they have to allow you to spend something otherwise anyone could just transfer anyone else's tokens.

From your frontend, you would have to call the approve function from the token contract. The user themself must approve. Of course you cannot approve for them that would defeat the point. I would recommend doing some reading on this area.

0
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

contract Shop {
    using SafeERC20 for IERC20;

    address usdtContractAddress;
    address usdtWalletOfShop;
    uint256 usdtBalanceOfShop;
    uint256 orderId;

    event Payment(address indexed user, uint256 amount, uint256 orderId);

    constructor(address _usdtContractAddress, address _usdtWalletOfShop) {
        usdtContractAddress = _usdtContractAddress;
        usdtWalletOfShop = _usdtWalletOfShop;
    }

    function order(uint256 amount) public {
        // Safely transfer tokens from user to shop.
        IERC20(usdtContractAddress).safeTransferFrom(msg.sender, usdtWalletOfShop, amount);

        // Update balance and order id, emit Payment event.
        usdtBalanceOfShop += amount;
        orderId += 1;
        emit Payment(msg.sender, amount, orderId);
    }
}

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.