In DeFi I have seen that users are prompted to give access to their funds. Why not just send those funds to the smart contract instead?
What is the advantage of this design?
Ethereum Stack Exchange is a question and answer site for users of Ethereum, the decentralized application platform and smart contract enabled blockchain. It only takes a minute to sign up.Sign up to join this community
There is no "advantage". The reason most DeFi apps ask users to "allow" the transfer of their funds is that those funds are represented as ERC-20 tokens. The Ethereum community is confronted with an instance of the classical path dependence problem.
Here's a guide that dives deep into ERC-20 allowances. And here are some practical solutions:
Generally, there are two ways to transfer (ERC20) tokens:
Direct transfer with
transfer. You can call this function to transfer your tokens directly to another address.
Indirect transfer with
transferFrom. This way you do two different transaction: first you give approval for the receiver to withdraw your tokens. Then you call some functionality in the receiver, and that executes
transferFrom which takes your tokens.
I think there are two advantages of using the indirect method:
Functionality. If you use a direct transfer, the receiver has no idea he has received tokens. You would anyway need a second transaction to tell the receiver that "hey, I sent you tokens, now do your part of the deal", and you'd suffer also in security. Also, with approvals, if you trust the receiver, you can just approve all of your tokens and do multiple trades with the same approval - so just one approval and multiple "second" transactions.
Security. It's harder to trick users into sending tokens to the wrong place if it requires two separate transactions. Also, this way you can in advance read the receiver's contract code and see what happens when you do the second transaction. With direct transfer you'd simply have to hope that the receiver does what it promised to do.