How to handle approve/allowance when using custom ERC20 token?

1.2k views Asked by At

Suppose I want to design a game where the user places a bet (using the ERC20 token) for a coin toss, and suppose the solidity function within our game contract called to place the bet is bet(uint256 _betAmount, int256 pick).
When playing around with some code, I realized that if the bet() function contains the token.transfer() call (used to place the initial bet before simulating the coin toss), the funds would be transfered from the game contract, and not from the user, even if the caller of bet() is the user. Thus, I would need to use the token.transferFrom() function, but the user would need to set the allowance for the game contract to spend the funds on their behalf.
My question is, how could this be handled in the frontend? Is there a way for a pop-up to show up asking for permission to spend the tokens (thinking of somehting similar to metamask when executing a transaction)?

1

There are 1 answers

0
Niccolò Fant On

Basically the user will need to accept two transactions. But before calling the bet function you need also to wait until the approve function is confirmed.

In a project i developed i also had to handle your exact same case and i did something like this (i used react-moralis to interact with the contract):

const handleBet = async () => {
  await approve({
    onSuccess: async (tx) => {
    
      await tx.wait(1) // Wait until the transaction is mined
   
      await bet() // Call the bet function
    },
    onError: () => {
      console.log("error") // Handle error however you want
    }
  })
}