1

I'm trying to understand how to call a solidity method from a web3 (dApp) and pay with an ERC20 token. I don't want to only transfer tokens, I want to execute the method & pay with the tokens instead of ethereum.

Which methods should be run from the frontend (web3) & which ones should be run from the Solidity smart contract?

Will the user need to approve two transactions from Metamask or only one will be needed?

Thanks

Antoni
  • 15
  • 3

1 Answers1

0

The user will have to approve 2 tx on Metamask the approval of the transfer and the solidity contract call. The approval must happen before calling the solidity function.

Using the ethers library as example this code migth better ilustrate the path you must follow:

 const factory = await new ethers.Contract(tokenAddress, tokenAbi, provider);
 const erc20 = await factory.attach(tokenAddress); //This will prompt the approval transaction to be approve

Then the solidity call to your contract, if you receive the transfer amount and the token address, if you will always use the same erc20 you could avoid sending the address:

await contract.connect(signer).deposit(depositamount, tokenAddress);

and your function must look something like this:

function deposit(uint _amount, address _token) external {
            IERC20 depositor =  IERC20(_token);            
            depositor.transferFrom(msg.sender, address(this), _amount);
}

Hope all these helps!

Julissa DC
  • 1,888
  • 1
  • 8
  • 21
  • In the ethers.Contract constructor, is the tokenAbi the ABI of the solidity contract? In your example, where the deposit method is located? Or is it the ABI of the ECR20 token? – Antoni Oct 20 '21 at 20:34
  • ethers.Contract intantiate a new contract, using the address and the token abi of its solidity contract, in my example the deposit method is inside my own solidity smart contract – Julissa DC Oct 20 '21 at 21:02
  • Can you add an example of the contract variable initialization? To use this method call await contract.connect(signer).deposit(depositamount, tokenAddress); – Antoni Oct 21 '21 at 05:33
  • You can check an implementation of what Im mentioning here: https://github.com/JulzCryptoMyriad/JulzWidget/blob/main/julzwidgetapp/src/components/PaymentComponent.js and the contract this is consuming is https://github.com/JulzCryptoMyriad/JulzUserWebPage/blob/main/webdapp/src/contracts/JulzPay.sol – Julissa DC Oct 21 '21 at 13:59