soliditysmartcontractsbep20

Implement IBEP20 interface in smart contract


contract Main  {
  string public name_ = "Test";

  mapping (address=>bool) addressIsApproved; 

  IBEP20 public immutable busd;
  constructor (IBEP20 _busdContract){
    busd = _busdContract;
  }


  function approve (uint256 _amount) public {
     bool isApproved =  IBEP20(busd).approve(msg.sender,_amount);
     addressIsApproved[msg.sender] = isApproved;
  }

  function buy(uint256 _amount) public returns (uint) {
      //
      bool isApproved = addressIsApproved[msg.sender];
      if (!isApproved) return 0;

      bool isPay =  IBEP20(busd).transferFrom(msg.sender,address(this), _amount);  
      if (!isPay) return 0;

      //do something...;
      
      return 1;
  }
}

I tried to charge BUSD in the contract, and when calling the Buy method, there is an error message: "insufficient allowance".


Solution

  • in the approve function, when you call IBEP20(busd).approve(msg.sender,amount) your contract is the one sending the transaction to the busd contract, so here you are not approving your contract to move the users token, you are doing the opposite, you are approving the user to move the tokens that the contract owns, if you want the user to approve the contract, the user should call first directly the approve function of the busd contract and then call the buy function