ethers.js是一个非常精简的以太坊操作库,它包含如下四个模块:
Ethers.provider
Ethers.contract
Ethers.utils
Ethers.wallets
其中,Ethers.provider负责与以太坊节点进行连接,查询交易、广播交易,获取账户余额等功能;
Ethers.contract负责与智能合约进行交互,包括部署合约、监听合约里的事件、获取合约里的信息,调用合约里的函数等功能;
Ethers.utils是一个工具库,主要用于处理输入、输出数据,数据的类型与格式转换;
Ethers.wallets主要用于创建新钱包,连接或切换现有钱包,以及对交易进行签名等功能。
下面,介绍使用Ethers.js来部署智能合约。
1、新建一个工程sendtokenone
mkdir sendtokenone
cd sendtokenone
npm init -y
truffle init
2、修改package.json并安装依赖包
a)修改后的package.json文件如下:
//package.json
{
"name": "sendtokenone",
"version": "1.0.0",
"description": "ethers.js部署合约",
"main": "",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@openzeppelin/contracts": "^3.4",
"@truffle/hdwallet-provider": "^1.5.0",
"bignumber": "^1.1.0",
"bignumber.js": "^8.1.1",
"chai": "^4.2.0",
"chai-as-promised": "^7.1.1",
"eslint": "^5.15.0",
"ethereumjs-tx": "^1.3.7",
"ethers": "^5.4.7",
"request": "^2.88.2",
"web3": "^1.3.0"
},
"devDependencies": {
"@babel/core": "^7.12.3",
"@babel/preset-env": "^7.12.1"
}
}
b) 安装依赖包
npm install
3、新建智能合约
3.1 创建一个EventValue.sol合约
在sendtokenone/contacts目录,创建一个创建一个EventValue.sol合约,内容如下:
// EventValue.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
contract EventValue {
event ValueChanged(address indexed author,uint oldValue,uint newValue);
uint _value;
constructor(uint value) public {
_value = value;
emit ValueChanged(msg.sender, _value, value);
}
function getValue() view public returns (uint) {
return _value;
}
function setValue(uint value) public {
_value = value;
emit ValueChanged(msg.sender, _value, value);
}
}
3.2 编写部署脚本
新建一个文件夹名称为migDeploy,然后在这个文件夹里,创建部署脚本1_deploy_event.js
mkdir migDeploy
cd migDeploy
touch 1_deploy_event.js
1_deploy_event.js的内容如下:
// sendtokenone/migDeploy/1_deploy_event.js
const {ethers} = require("ethers")
const fs = require('fs')
let provider = new ethers.providers.JsonRpcProvider('http://localhost:8545')
function getHexString(prikeyPath) {
const privKeyFile = fs.readFileSync(prikeyPath).toString().trim();
const privKey = new Buffer.from(privKeyFile, 'hex');
return privKey
}
// var privKey = getHexString(".secret")
var privKey = '0x403d...23d5'
let wallet = new ethers.Wallet(privKey,provider)
var jsonStr = fs.readFileSync('./build/contracts/EventValue.json')
var jsonInfo = JSON.parse(jsonStr)
var jsonAbi = jsonInfo.abi
var bytecode = jsonInfo.bytecode
async function deployContract(abi,bytecode,wallet) {
let factory = new ethers.ContractFactory(abi,bytecode,wallet)
let contractObj = await factory.deploy(100)
console.log('contractAddress=',contractObj.address)
console.log('deploy txHash=',contractObj.deployTransaction.hash)
await contractObj.deployed()
}
deployContract(jsonAbi,bytecode,wallet)
3.3 编译合约
a)设置ganache的IP为127.0.0.1,端口为8545
b) 在truffle-config.js里,开启development网段、solc指定版本为0.6.6,具体如下:
// truffle-config.js
module.exports = {
networks: {
development: {
host: "127.0.0.1", // Localhost (default: none)
port: 8545, // Standard Ethereum port (default: none)
network_id: "*", // Any network (default: none)
},
},
// Set default mocha options here, use special reporters etc.
mocha: {
// timeout: 100000
},
// Configure your compilers
compilers: {
solc: {
version: "0.6.6", // Fetch exact version from solc-bin (default: truffle's version)
// docker: true, // Use "0.5.1" you've installed locally with docker (default: false)
// settings: { // See the solidity docs for advice about optimization and evmVersion
// optimizer: {
// enabled: false,
// runs: 200
// },
// evmVersion: "byzantium"
// }
}
},
};
打开一个黑框框控制台,使用truffle编译该合约
cd sendtokenone
truffle console
compile
3.4 部署合约
在黑框框终端里,输入如下命令,即可部署合约
cd sendtokenone
node migDeploy\1_deploy_event.js
效果如下:
可以打印合约地址和txHash,说明合约部署成功。