0
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".

DougZo
  • 23
  • 9

1 Answers1

1

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

jhonny
  • 805
  • 4
  • 10
  • Sorry, I'm not sure, can you give me some examples please? I'm newbie for solidity. – DougZo Dec 03 '21 at 18:17
  • 1
    is mostly a frontend thing, it depends in the tools you are using but is simply performing a call to the token contract calling the approve function – jhonny Dec 05 '21 at 02:54