0

hello Me and my team are working on a staking/subscribing dApp on the ethereum blockchain using erc20 stablecoins like usdt and dai. We encounterd an error on the approve() and transferfrom() functions, and we need help.

How can write a code that allows a user to approve our dapp contract to transfer usdt on his behalf, and also allows the contract admin to transfer the token when the function transferfrom() is called? this is actually needed for the subscribe part of our dapp.

2 Answers 2

0

When you call approve(), you are allowing a specified address to take a certain amount of tokens from your address.

So in your case, I guess you would have to call it twice. (Once to allow contract address to take tokens, and second time to allow admin to transfer them)

0

Firstly, you need to implement approve button in the UI, when user clicks it, approval should be called like this:

IERC20(_tokenAddress).approve(ADDRESS_OF_YOUR_DAPP, amount)

Where _tokenAddress is an address which we can get from the input field in the UI (for example, user can choose token to deposit in some dropdown menu) and _amount is a value that we can also get from the UI. Then, when approval is done, when a user clicks on some Deposit button, you should execute your deposit function from your smart-contract, inside which transferFrom should be implemented like this:

IERC20(_tokenAddress).transferFrom(msg.sender, address(this), _amount)

Secondly, don't fully get your idea of

allows the contract admin to transfer the token when the function transferfrom() is called

If you need to transfer this tokens from dapp contract to admin contract, you can do just:

IERC20(_tokenAddress).transfer(ADDRESS_OF_ADMIN, _amount)

Or if you need to allow to admin contract to transfer tokens from dapp contract, you need to call approve inside dapp contract itself:

IERC20(_tokenAddress).approve(ADDRESS_OF_ADMIN, _amount)

And then if you want, you can call transferFrom inside the admin contract to transfer tokens from dapp contract.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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