1

I am working on a basic staking platform for practice. I understand that the user of the platform has to call the approve() function and pass the contract into it in order for the contract to use the transferFrom(). However, as a beginner I don't know how to call that function from the perspective of the "user," in this case, my test accounts. How can I increase the allowance of a token that is already on the network?

1
  • Hi! We could use a bit more information - could you edit the question to include what framework or library you're using to connect to the blockchain you're using? (It might be useful to know what chain it is to, such as Hardhat Network, Ganache, or a testnet.) – The Renaissance Mar 21 at 8:30
0

Welcome!

As you stated, a contract can only transfer tokens from a user if the user has already approved the contract to spend the tokens. It is important to recognize that the user will call approve() on the token contract before interacting with your contract.

In practice, a dapp will usually ask a user to perform two transactions:

  • tokenContract.approve(yourContractAddress, amount);
  • yourContract.yourFunction(); // This function has tokenContract.transferFrom()
2
  • 1
    I understand this, but in a testing environment (without setting up a front end), how can I ask the user to perform these transactions? I could be wrong, but simply putting the approve() function in the contract and having the user call that doesn't work, does it? – user68609 Mar 20 at 22:56
  • I see. In a testing environment, you can import the ERC20 interface and attach an existing address to it. If you are using ethers.js, for example, you can use erc20Token = ERC20Token.attach(erc20TokenAddress); and then you can all erc20Token.approve(). You can see more from the official docs here. – Shane Fontaine Mar 20 at 23:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.