2022-10-11Web300
请注意,本文编写于 613 天前,最后修改于 613 天前,其中某些信息可能已经过时。

依赖项

package.json

{
  "dependencies": {
    "dotenv": "^16.0.3",
    "ethers": "^5.7.1",
    "fs-extra": "^10.1.0",
    "prettier": "^2.7.1",
    "prettier-plugin-solidity": "^1.0.0-beta.24",
    "solc": "0.8.7-fixed"
  },
  "scripts": {
    "compile": "yarn solcjs --bin --abi --include-path node_modules/ --base-path . -o . SimpleStorage.sol"
  }
}

搭建本地 Ethereum blockchain

官网:ganache

Quickly fire up a personal Ethereum blockchain which you can use to run tests, execute commands, and inspect state while controlling how the chain operates.

image.png

ethers.js

官网: https://learnblockchain.cn/docs/ethers.js/

ethers.js 库是为以太坊 提供的一个的小而完整的 JavaScript 库。

安装ethers

npm install --save ethers

导入ethers

const ethers = require('ethers');

示例代码

deploy.js

const ethers = require("ethers");
const fs = require("fs-extra");

async function main() {
  // 连接本地 ganache 平台的RPC SERVER
  const provider = new ethers.providers.JsonRpcProvider(
    "http://127.0.0.1:7545"
  );
  // 创建钱包 传入private_key和provider
  const wallet = new ethers.Wallet(
    "576426909a6cd4d33c8cffe7001144f6676a2fb6d7508f5aa1f1965ce783cda8",
    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(); // 返回promise, so stop here!
  const deploymentReceipt = await contract.deployTransaction.wait(1);
  // 交易票据
  console.log(deploymentReceipt);
  // transaction response
  console.log(contract.deployTransaction);
  // 获得nonce
  const nonce = wallet.getTransactionCount();
}

main()
  .then(() => {
    process.exit(0);
  })
  .catch((err) => {
    console.log(err);
    process.exit(1);
  });

总结

ethers.js可以说是一个比较小的javascript库,用来与以太坊进行交易。我们需要更强大的一个框架来完成这些事情。智能合约开发框架Hardhat

image.png

image.png

本文作者:前端小毛

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!