实现ETH和ERC20兑换功能的合约,无法扣除调用者的ETH,需要将 ETH 转化为某种ERC20 标准的代币, 才能执行智能合约中币币兑换的操作,目前大家认可度最高的就是WETH这个代币。
ERC20部分使用openzeppelin的实现,在此基础上增加ETH <=> WETH的相互兑换
ETH => WETH
接收以太坊可以使用回退函数,在回退函数里给调用者地址发型相同数量的WETH代币
receive() external payable {
require(msg.value > 0);
_mint(msg.sender, msg.value);
}
WETH => ETH
根据ERC20代币标准转账对应的函数是transfer,可以在这个函数里增加一段逻辑,如果是转账给合约本身就把相同数量的以太坊发送给调用者地址
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
if (recipient == address(this)) {
_burn(msg.sender, amount);
msg.sender.transfer(amount);
} else {
_transfer(_msgSender(), recipient, amount);
}
return true;
}
如果想自己尝试发布可以从下面这个地址把demo代码下载到本地
https://github.com/typ0520/WETH
合约代码如下所示
pragma solidity ^0.6.12;
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
contract WETH is ERC20 {
constructor() public ERC20('WETH', 'WETH') {
}
receive() external payable {
require(msg.value > 0);
_mint(msg.sender, msg.value);
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
if (recipient == address(this)) {
_burn(msg.sender, amount);
msg.sender.transfer(amount);
} else {
_transfer(_msgSender(), recipient, amount);
}
return true;
}
}
进入合约目录执行npm install把依赖的包下载到本地,然后在当前目录下创建.secret文件并把私钥配置进去,接下来执行迁移命令把合约发布到ropsten测试链
yarn truffle migrate --network ropsten --reset
等待合约创建交易确定完成
使用合约地址0x9c529F6251D3C560a1d0314dFA6697eaBE45C893,打开truffle的console交互环境做测试,可以直接在终端使用web3
yarn truffle console --network ropsten
首先把WETH的实例创建出来
var token = await WETH.at('0x9c529F6251D3C560a1d0314dFA6697eaBE45C893');
测试ETH兑换WETH
测试的流程是首先查询以太币余额和WETH余额,然后给合约地址转以太币,最后再次查询以太坊余额和WETH余额
- 查询以太币余额和WETH余额
//获取当前账户地址
var userAddress = (await web3.eth.getAccounts())[0];
//查询以太币余额
var firstEthBalance = await web3.eth.getBalance(userAddress);
web3.utils.fromWei(firstEthBalance);
//查询WETH余额
var firstWthBalance = await token.balanceOf(userAddress);
web3.utils.fromWei(firstWthBalance);
- 转给合约0.1以太币兑换0.1的WETH
await web3.eth.sendTransaction({from: userAddress, to: '0x9c529F6251D3C560a1d0314dFA6697eaBE45C893', value: web3.utils.toWei('0.1', 'ether')});
- 再次查询以太坊余额和WETH余额
//查询以太币余额
var secondEthBalance = await web3.eth.getBalance(userAddress);
web3.utils.fromWei(secondEthBalance);
//查询WETH余额
var secondWethBalance = await token.balanceOf(userAddress);
web3.utils.fromWei(secondWethBalance);
测试WETH兑换ETH
- 把WETH转给合约换回以太坊
await token.transfer('0x9c529F6251D3C560a1d0314dFA6697eaBE45C893',web3.utils.toWei('0.1', 'ether'));
- 查询以太坊余额和WETH余额
//查询以太币余额
var thirdEthBalance = await web3.eth.getBalance(userAddress);
web3.utils.fromWei(thirdEthBalance);
//查询WETH余额
var thirdWethBalance = await token.balanceOf(userAddress);
web3.utils.fromWei(thirdWethBalance);