I want to achieve the following flow:

  • A user clicks a button allowing my contract to spend funds on the user's behalf
  • A user clicks a second button whereupon funds are transferred from the user's wallet to the contract.

From my understanding this needs to be split up into two transactions.

So i thought something like this would work:

Contract code:

function approve(uint amount) public {
  // Calling this function first from remix
  ERC20(Token_address).approve(address(this), amount)

function transferFrom(uint amount) public {
  // Then calling this function from remix
  ERC20(Token_address).transferFrom(msg.sender, address(this), amount)

But it gives me gas estimation failiure inside of remix. I suspect this is because i cannot have the contract call the approve() function. It needs to be called from the user whom is approving the contract to withdraw its funds. How can i achieve this if the user isn't a another smart contract but just a person with a metamask wallet?

  • 1
    The user should call approve, not the contract. – goodvibration Mar 2 at 15:59

You're right, the contract can't call itself the "approve" method. Instead you can write a script. An exemple with web3js 1.2 could be :

var erc20Instance = new web3.eth.Contract(abi,Token_address);

erc20Instance.methods.approve(contractAddress, amount).send({from: userAddress}, 
function(err, transactionHash) {
//some code

with :

  • abi : the abi of the token contract. You can use https://github.com/ethereum/wiki/wiki/Contract-ERC20-ABI for an ERC20.
  • contractAddress : the address of the contract to approve.
  • amount : the amount to approve. Note that you can "disapprove" the contract by sending a new transaction with an amount of 0, as it will override the previous value.
  • userAddress : the sender's address.
| improve this answer | |

The approve function is used to set allowance for the current sender. If you would call it from your own contract, you would approve spending the tokens for your own contract.

Instead of calling approve through a smart contract, you have to send the transaction directly from the user to the ERC-20 contract, with the address of your own smart contract specified as _sender. To do this, just send a transaction using MetaMask's API.

| improve this answer | |

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.