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?
Best Answer
You're right, your contract should not call the
approve
method itself, as it would become themsg.sender
in the context of the token smart contract, which would cause your contract to self-approve.You want the user to approve your contract and you can write a script to achieve this. An exemple with web3js 1.2 could be :
with :