0

I'm confused about how I write a contract about WETH conversion.

When we write a smartcontract depositing user funds into a contract, should we necessarily write some codes of converting eth into weth before depositing? Or is it automatically converted without doing anything?

I've found descriptions about WETH on the uniswap's router contract( function addLiquidityETH) which is called when users provide the liquidity for the uniswap pool.

IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));

*https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/UniswapV2Router02.sol

On the other hand, for example, join.sol(function join) on MakerDAO's vault contract and CEther.sol(function doTransferIn) on Compound's Ctoken contract, I can't see anything about weth even though they seem the functions to deposit eth into a contract.

*https://etherscan.io/address/0x2f0b23f53734252bda2277357e97e1517d6b042a#code

function join(address usr) external payable note {
require(live == 1, "ETHJoin/not-live");
require(int(msg.value) >= 0, "ETHJoin/overflow");
vat.slip(ilk, usr, int(msg.value));

*https://github.com/compound-finance/compound-protocol/blob/master/contracts/CEther.sol

function doTransferIn(address from, uint amount) internal returns (uint) { 
// Sanity checks 
require(msg.sender == from, "sender mismatch");
require(msg.value == amount, "value mismatch");
return amount; }

And what I want to do after I make sure above problem is write a contract where user can deposit ETH into another contract by interecting with this contract. I know if a user has WETH, it's easy bc all i have to do is write function transferfrom but I don't know how to do it with ETH itself.

0

WETH is an ERC20 token that has 1:1 mapping from ether to WETH.

To obtain WETH you have to call function deposit with an the ether amount you want to convert to WETH. In javascript it will look like:

WETH.methods.deposit().send({
    value:  etherAmount,
    from: userAddress
});

Conversely to withdraw ethers you have to call function withdraw with the WETH amount you to retrieve.

WETH.methods.withdraw(wethAmount).send({
    from: userAddress
});

Some contracts like Uniswap or MakerDAO uses WETH to simplify its workflow since it is an ERC20 and they don't have to make exceptions for handling ethers.

1
  • Thanks! it's really helpful.
    – wat
    Oct 24 '20 at 13:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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