Skip to main content

WETH

WETH 合约地址: 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 Etherscan: https://etherscan.io/address/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2

WETH 合约源码

pragma solidity ^0.4.18;

contract WETH9 {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;

event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
event Deposit(address indexed dst, uint wad);
event Withdrawal(address indexed src, uint wad);

mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;

function() public payable {
deposit();
}

// ETH -> WETH
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
Deposit(msg.sender, msg.value);
}
// WETH -> ETH
function withdraw(uint wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
msg.sender.transfer(wad);
Withdrawal(msg.sender, wad);
}

function totalSupply() public view returns (uint) {
return this.balance;
}

function approve(address guy, uint wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
Approval(msg.sender, guy, wad);
return true;
}

function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}

function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
require(balanceOf[src] >= wad);

if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}

balanceOf[src] -= wad;
balanceOf[dst] += wad;

Transfer(src, dst, wad);

return true;
}
}

ETH 和 WETH 1:1 兑换

  1. ETH 兑换成 WETH

调用 WETH 的deposit方法,msg.value即表示要兑换的数量

  1. WETH 兑换成 ETH

调用 WETH 的withdraw方法