solidity之通过ethers.js部署合约

587 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10月更文挑战」的第9天,点击查看活动详情

前言

前面讲过remix部署智能合约,确实比较方便,更多的是方便调试。但是有些时候我们想通过一些脚本来操作,这时候就需要建立对应的项目来编译,通过一些工具库来进行编译。

安装节点工具Ganache

Ganache可以快速启动个人以太坊区块链,并可以使用它来运行测试,执行命令、检查状态,同时控制链条的运行方式。

下载地址 github.com/trufflesuit…

安装完成点击启动后可得到一条私链,我们可以用来练习。如下图,我们可以选择其中一个地址,拿到其中的私钥记录在我们的文件里用来测试。

image.png

搭建项目

  • 新建一个文件夹,新建package.json,安装依赖,solc、ethers.js等

npm install solc@0.8.7-fixed //这是solidity编译版本

npm install ethers //ethers.js库

npm install dotenv //设置环境变量.env

npm install fs-extra //文件读取

  • 新建一个.env文件用来配置我们的私钥和rpc地址,

image.png

let provider = new ethers.providers.JsonRpcProvider(process.env.RPC_URL)
let wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider)
  • 编译solidity合约文件,执行下面命令,可配置在package.json里面
yarn solcjs --bin --abi --include-path node_modules/ --base-path . -o . SimpleStorage.sol

可生成合约的abi和bin文件

image.png

  • 新建deploy.js
const ethers = require("ethers")
const fs = require("fs-extra")
require("dotenv").config()

async function main() {
    // First, compile this!
    // And make sure to have your ganache network up!
    let provider = new ethers.providers.JsonRpcProvider(process.env.RPC_URL)
    let wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider)
    const abi = fs.readFileSync("./SimpleStorage_sol_SimpleStorage.abi", "utf8")
    const binary = fs.readFileSync(
        "./SimpleStorage_sol_SimpleStorage.bin",
        "utf8"
    )
    const contractFactory = new ethers.ContractFactory(abi, binary, wallet)
    console.log("Deploying, please wait...")
    const contract = await contractFactory.deploy()
    const deploymentReceipt = await contract.deployTransaction.wait(1)
    console.log(`Contract deployed to ${contract.address}`)

    let currentFavoriteNumber = await contract.retrieve()
    console.log(`Current Favorite Number: ${currentFavoriteNumber}`)
    console.log("Updating favorite number...")
    let transactionResponse = await contract.store(7)
    let transactionReceipt = await transactionResponse.wait()
    currentFavoriteNumber = await contract.retrieve()
    console.log(`New Favorite Number: ${currentFavoriteNumber}`)
}

main()
    .then(() => process.exit(0))
    .catch((error) => {
        console.error(error)
        process.exit(1)
    })

完整的package.json配置如下

{
  "name": "etherSimple",
  "version": "1.0.0",
  "dependencies": {
    "dotenv": "^16.0.1",
    "ethers": "^5.6.9",
    "fs-extra": "^10.1.0",
    "solc": "^0.8.7-fixed"
  },
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "compile": "yarn solcjs --bin --abi --include-path node_modules/ --base-path . -o . SimpleStorage.sol"
  }
}

合约部署

执行 node deploy.js

image.png

接着可以查看我们的Ganache工具,点击交易模块,可以看到了2条交易,一条是创建合约的交易,一个是合约的方法调用

image.png

总结

ethers.js库旨在为以太坊区块链及其生态系统提供一个小而完整的 JavaScript API 库,这里只是介绍了一个基础使用,同时如果真实环境私钥不要暴露出去。