前言
实现一个带包装的原生代币,对该合约进行开发、测试、部署以及对使用场景介绍的
包装原始代币使用场景
ETH原始币本身是不符合ERC20代币标准,为了提高区块链之间的互操作性 ,并使ETH可用于去中心化应用程序(dApps),所有给ETH包一层智能合约。
合约开发
合约说明:继承ERC20代币标准,新增加了存款和提款两个功能;
// SPDX-License-Identifier: MIT
// Compatible with OpenZeppelin Contracts ^5.0.0
pragma solidity ^0.8.22;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract WETH is ERC20{
// 事件:存款和取款
event Deposit(address indexed dst, uint wad);
event Withdrawal(address indexed src, uint wad);
// 构造函数,初始化ERC20的名字
constructor() ERC20("WETH", "WETH"){
}
// 回调函数,当用户往WETH合约转ETH时,会触发deposit()函数
fallback() external payable {
deposit();
}
// 回调函数,当用户往WETH合约转ETH时,会触发deposit()函数
receive() external payable {
deposit();
}
// 存款函数,当用户存入ETH时,给他铸造等量的WETH
function deposit() public payable {
_mint(msg.sender, msg.value);
emit Deposit(msg.sender, msg.value);
}
// 提款函数,用户销毁WETH,取回等量的ETH
function withdraw(uint amount) public {
require(balanceOf(msg.sender) >= amount);
_burn(msg.sender, amount);
payable(msg.sender).transfer(amount);
emit Withdrawal(msg.sender, amount);
}
}
# 编译指令
# npx hardhat compile
合约测试
const {ethers,getNamedAccounts,deployments} = require("hardhat");
const { assert,expect } = require("chai");
describe("WETH",function(){
let WETH;//合约
let firstAccount//第一个账户
let secondAccount//第二个账户
beforeEach(async function(){
await deployments.fixture(["weth"]);
firstAccount=(await getNamedAccounts()).firstAccount;
secondAccount=(await getNamedAccounts()).secondAccount;
const WETHDeployment = await deployments.get("WETH");
WETH = await ethers.getContractAt("WETH",WETHDeployment.address);//已经部署的合约交互
});
describe("WETH",function(){
it("WETH交易",async function(){
//存100个eth
await WETH.deposit({value:100})//100000000000000000000
console.log(await WETH.balanceOf(firstAccount))
//给secondAccount转账10个weth
await WETH.transfer(secondAccount,10)
console.log(await WETH.balanceOf(firstAccount))
console.log(await WETH.balanceOf(secondAccount))
//把firstAccount账号的weth转成eth
await WETH.withdraw(10)
console.log(await WETH.balanceOf(firstAccount))
});
});
})
# 测试指令
# npx hardhat test ./test/xxx.js
合约部署
module.exports = async function ({getNamedAccounts,deployments}) {
const firstAccount= (await getNamedAccounts()).firstAccount;
const {deploy,log} = deployments;
const WETH=await deploy("WETH",{
from:firstAccount,
args: [],//参数
log: true,
})
console.log("WETH合约",WETH.address)
}
module.exports.tags=["all","weth"]
# 部署指令
# npx hardhat deploy
总结
以上就是包装原始代币的合约的开发,测试,部署整个过程。包装原始代币合约目的就是让原始币套一层合约让它符erc20标准,从而实现跨链等能力。合约与erc20代币合约新增加了存款和取款的方法。