I'm writing a contract which should handle both ether (Ξ) and ERC20 tokens. I know that many dApps use WETH and I understand what it does, but I'm not sure if it's used because it's the most efficient in terms of avoiding writing code logic twice, gas costs etc - or some other reason?
1 Answer
WETH exists in order to allow ETH to follow the ERC20 standard. This gives developers the ability to write consistent code that allows Dapps to simply use either ETH or ERC20 tokens, and not have to worry about interactions between the two. Additionally, there are certain functions of ERC20 tokens that ETH does not have.
The best example to understand this is by thinking about decentralized exchanges. DEXs are written in such a way that they interact with ERC20 tokens and require WETH to be used (as opposed to ETH). The reason this is necessary is because ERC20 tokens have functionality that ETH does not.
A decentralized exchange trade works as follows: the maker of each trade must first call the ERC20 approve
function for the token they are attempting to trade (which allows the exchange contract to send the user's tokens on their behalf). The maker then posts his order in the orderbook and waits for it to be filled. When the taker fills the order, the ERC20 function transferFrom
is called, which transfers the ERC20 token from the maker to the taker, thus completing the trade. These actions are not possible with ETH, as there are no approve
and transferFrom
functions built into ETH itself.
WETH (as well as PETH) is also seen in the MakerDAO ecosystem.
There is a canonical WETH contract that is used by almost everyone in the network.
-
1Thank you for your explanation. So, just to confirm, a decentralised exchange could technically be implemented with native Ξ but it would be highly unwieldy? Commented Nov 13, 2018 at 9:34
-
It would depend on the architecture. The exchange contract would have to receive the ETH from the maker and hold custody until a taker initiates a trade. I imagine the ERC20 aspect would work similarly to my answer above. I have not thought through it all, so I am not sure this is totally feasible. Commented Nov 13, 2018 at 10:30