首页 > 其他分享 >4.区块链系列之本地环境从0到1部署智能合约

4.区块链系列之本地环境从0到1部署智能合约

时间:2022-10-29 15:58:33浏览次数:148  
标签:favoriteNumber const -- contract 智能 SimpleStorage 本地 区块 ethers

本文讲解使用本地开发工具编写、部署智能合约。

  • 准备环境
    • Visual Studio Code
    • Node
    • 安装solidity插件,如图所示:
      1
    • 同理安装Prettier - Code formatter插件
      安装插件后,重启Visual Studio Code
PS D:\blockchain\ehthers-simple-storage-fcc> node --version
v16.4.1

1. 新建SimpleStorage.sol文件

// SPDX-License-Identifier: MIT

pragma solidity 0.8.7;

contract SimpleStorage {
    uint256 favoriteNumber;

    struct People {
        uint256 favoriteNumber;
        string name;
    }
    People[] public people;

    mapping(string => uint256) public nameToFavoriteNumber;

    function store(uint256 _favoriteNumber) public {
        favoriteNumber = _favoriteNumber;
    }

    function retrieve() public view returns (uint256) {
        return favoriteNumber;
    }

    function addPerson(string memory _name, uint256 _favoriteNumber) public {
        people.push(People(_favoriteNumber, _name));
        nameToFavoriteNumber[_name] = _favoriteNumber;
    }
}

2. 新建.vscode/settings.json中添加格式化插件

{
    "[solidity]": {
        // 默认代码格式化方式
        "editor.defaultFormatter":"NomicFoundation.hardhat-solidity"
    },
    "[javascript]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    }
}

3. 编译solidity

# 由于npm版本低于16.10
# 详见https://yarnpkg.com/getting-started/install#install-corepack
npm i -g corepack
yarn add [email protected]

yarn solcjs --bin --abi --include-path node_modules/ --base-path . -o . SimpleStorage.sol

现在我们把脚本放置到package.json中,下次直接点击即可编译

{
  "dependencies": {
    "solc": "0.8.7-fixed"
  },
  "scripts": {
    "compile": "yarn solcjs --bin --abi --include-path node_modules/ --base-path . -o . SimpleStorage.sol"
  }
}

4. 安装ganache

https://trufflesuite.com/ganache/

windows开发者设置,打开开发者模式,然后进入powershell

Add-AppxPackage -Path "D:\Users\Domi\Downloads\Ganache-2.5.4-win-x64.appx"

启动应用后,找到
RPC SERVER:http://127.0.0.1:7545
NETWORK ID:5777

4

5.新建deploy.js

const ethers = require("ethers");
const fs = require("fs-extra");
require("dotenv").config();

async function main() {
  let provider = new ethers.providers.JsonRpcProvider(process.env.RPC_URL);
  // 私钥不加密方式,开发
  let wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider);

  // 生产环境私钥一定要加密,并且history历史命令记录也要清空,否则后果自负!!!!!!!!
  // const encryptedJson = fs.readFileSync("./.encryptedKey.json", "utf8");
  // let wallet = new ethers.Wallet.fromEncryptedJsonSync(
  //   encryptedJson,
  //   process.env.PRIVATE_KEY_PASSWORD
  // );
  // wallet = wallet.connect(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);
  });

新建.env配置文件

# 随便找个本地ganache账户address的私钥【点击

标签:favoriteNumber,const,--,contract,智能,SimpleStorage,本地,区块,ethers
From: https://www.cnblogs.com/shenjian-online/p/16838895.html

相关文章