Last active
March 18, 2022 09:18
-
-
Save a2468834/e68d62e019f88c2d0ba28d9bca472900 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: GPL-3.0 | |
pragma solidity >=0.8.1 <0.9.0; | |
/** | |
* @dev | |
* The original contract: | |
* https://etherscan.io/address/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2#code | |
*/ | |
interface IWeth9 { | |
function allowance(address, address) external returns (uint256); | |
function deposit() external payable; | |
function withdraw(uint256) external; | |
function transferFrom(address, address, uint256) external returns (bool); | |
} | |
/** | |
* @dev | |
* This contract will deposit and withdraw eth through calling WETH contract | |
*/ | |
contract ShortAns { | |
IWeth9 immutable WETH; | |
event Log(string event_msg); | |
// The contructor argument must be the address of Wrapped Ether contract | |
constructor(address payable _address) { | |
WETH = IWeth9(_address); | |
} | |
function userDeposit() public payable returns (bool) { | |
address user = msg.sender; | |
address this_contract = address(this); | |
// Deposit eth | |
try WETH.deposit{value: msg.value}() { // balanceOf[this_contract] += msg.value | |
emit Log("Message call OK"); | |
} | |
catch { | |
emit Log("Message call failed: deposit()"); | |
return false; | |
} | |
// Transfer weth to msg.sender's address | |
try WETH.transferFrom(this_contract, user, msg.value) { | |
emit Log("Message call OK"); | |
} | |
catch { | |
emit Log("Message call failed: transferFrom()"); | |
return false; | |
} | |
return true; | |
} | |
function userWithdraw(uint256 amount) public returns (bool) { | |
address user = msg.sender; | |
address this_contract = address(this); | |
require(WETH.allowance(user, this_contract) >= amount, "Withdraw failed: you must approve enough allowance"); | |
// Transfer weth to this contract | |
try WETH.transferFrom(user, this_contract, amount) { | |
emit Log("Message call OK"); | |
} | |
catch { | |
emit Log("Message call failed: transferFrom()"); | |
return false; | |
} | |
// Withdraw weth | |
try WETH.withdraw(amount) { | |
emit Log("Message call OK"); | |
} | |
catch { | |
emit Log("Message call failed: withdraw()"); | |
return false; | |
} | |
// Send eth to msg.sender | |
(bool ack, ) = payable(user).call{value: amount}(""); | |
return ack; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment