ERC-20 – How to Receive ERC20 Tokens in Smart Contract?

erc-20

Hello I'm pretty new to ERC20 and i try to research something but maybe concept in my head is not correct. I'm trying to create smart contract that is receiving some amount of ERC20, validating the input amount and if it's ok it continue with logic below. Smart contract looks something like this:

contract Orders {
 uint256 public counter;

 function deposit() public payable {
   // Here we validate if sended USDT for example is higher than 50, and if so we increment the counter

  counter = counter + 1
 }
}

How to validate sended amount of ERC20 for each individual deposit

Best Answer

Try this:

//SPDX-License-Identifier: MIT
pragma solidity 0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract Orders is Ownable {
  uint256 public counter;
  address token;

  constructor(address _token) {
    token = _token;
  }

  function deposit(uint _amount) public payable {
    // Set the minimum amount to 1 token (in this case I'm using LINK token)
    uint _minAmount = 1*(10**18);
    // Here we validate if sended USDT for example is higher than 50, and if so we increment the counter
    require(_amount >= _minAmount, "Amount less than minimum amount");
    // I call the function of IERC20 contract to transfer the token from the user (that he's interacting with the contract) to
    // the smart contract  
    IERC20(token).transferFrom(msg.sender, address(this), _amount);
    counter = counter + 1;
  }

  // This function allow you to see how many tokens have the smart contract 
  function getContractBalance() public onlyOwner view returns(uint){
    return IERC20(token).balanceOf(address(this));
  }
}

NOTE: Remember to approve the smart contract to spend your tokens.

Related Topic