Home > Mobile >  Call erc20 approve function using ethers.js
Call erc20 approve function using ethers.js

Time:09-04

I was developing a front end for a smart contract using React JS and ethers.js. The smart contract has the following function.

function buyPremiumSpin(uint256 spins) external {
    require(spins > 0, "You can't get 0 premium spins!");
    uint256 cost = premiumSpinPrize * spins;
    require(wblock.balanceOf(msg.sender) >= cost, "Not enough WBLOCKS!");
    wblock.transferFrom(msg.sender, address(teamWallet), cost);
    premiumSpins[msg.sender]  = spins;
}

I tried to call the function using

const signer = provider.getSigner();
const contract = new ethers.Contract(CONTRACT_ADDRESS, abi, signer);

const transaction = await contract.buyPremiumSpin(
    spins,
    {gasLimit: gasLimit}
);  

But the transaction failed with message Fail with error 'ERC20: insufficient allowance'.

After some research I found out approve function in erc20. That user has to approve an address to let them transfer tokens. But I couldn't implement it using javascript.

I tried

contract.approve(account, premiumSpinPrize, {gasLimit:gasLimit})

But failed due to javascript error because approve wasn't a function.

What is the correct way to execute the smart contract function? Also it would be great if user could approve maximum amount so they don't have to approve it every time.

CodePudding user response:

The approval happens on the ERC20 smart contract to give approval to your smart contract to spend the tokens on your behalf. You just need to grab the Token ABI and instantiate a contract instance of the Token like you did above with your contract ;)

var tokenContract = new ethers.Contract(tokenAddress, tokenABI, provider);
tokenContract.approve(<Your_Contract_Address>, amount, {gasLimit: gasLimit})
  • Related