美文网首页
01 hardhat-初始化第一个合约

01 hardhat-初始化第一个合约

作者: AveryWang | 来源:发表于2022-10-05 20:48 被阅读0次

    1 初始化项目及依赖

    mkdir hardhat-sol-demo
    cd hardhat-sol-demo
    
    yarn init -y
    yarn add -D hardhat
    yarn add -D @nomiclabs/hardhat-ethers ethers @nomiclabs/hardhat-waffle ethereum-waffle chai
    yarn add -D ts-node typescript
    yarn add -D chai @types/node @types/mocha @types/chai
    yarn add -D hardhat-abi-exporter
    yarn add -D hardhat-contract-sizer
    yarn add -D hardhat-gas-reporter
    

    2 hardhat 初始化

    npx hardhat
    

    选择 Create an empty hardhat.config.js 创建空的配置

    image.png

    修改 hardhat.config.js => hardhat.config.ts

    编辑 hardhat.config.ts

    /** @type import('hardhat/config').HardhatUserConfig */
    import "@nomiclabs/hardhat-waffle"
    import "@nomiclabs/hardhat-ethers"
    import "hardhat-abi-exporter";
    import "hardhat-gas-reporter";
    import "hardhat-contract-sizer";
    
    module.exports = {
      solidity: "0.8.17",
      networks: {
        // bsctest
        bsctestnet: {
          url: 'https://data-seed-prebsc-1-s1.binance.org:8545/',
          gasPrice: 20000000000,
          gas: 4100000,
          chainId: 97,
          accounts: ['bscnst 链账户密钥'],
        }
      },
      gasReporter: {
        enabled: true,
        showMethodSig: true,
        maxMethodDiff: 10,
        currency: 'USD',
        gasPrice: 127,
      },
      contractSizer: {
        alphaSort: true,
        runOnCompile: true,
        disambiguatePaths: false,
      },
      paths: {
        sources: "./contracts",
        tests: "./test",
        cache: "./cache",
        artifacts: "./artifacts"
      },
      abiExporter: {
        path: './abi',
        runOnCompile: true,
        clear: true,
        spacing: 2
      }
    };
    
    
    

    建立合约文件夹

    mkdir contracts
    

    编写合约 contracts/Demo.sol

    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;
    
    contract Demo {
        uint256 private _number;
    
        // 记录 number 变化log
        event IncrNumberEvent(uint256 oldNumber, uint256 newNumber);
    
        // 增加 number 值
        function IncrNumber(uint256 number) public {
            uint256 oldNumber = _number;
            _number = oldNumber + number;
            emit IncrNumberEvent(oldNumber, _number);
        }
    
        // 获取 number 值
        function GetBumber() public view returns (uint256) {
            return _number;
        }
    }
    

    测试合约

    新增 test 文件夹

    mkdir test
    

    编写测试脚本 test/Demo.ts

    import { ethers } from "hardhat";
    import { expect } from "chai";
    
    describe("Demo", () => {
        let demo
    
        // 部署合约 默认部署环境为 hardhat 提供
        before(async () => {
            const Demo = await ethers.getContractFactory("Demo")
            const deploy = await Demo.deploy()
            demo = await deploy.deployed()
        })
    
        it("incr", async () => {
            // 调用合约
            await demo.IncrNumber(10)
    
            // 获取合约值,理论上第一次调用结果集为10
            expect((await demo.GetNumber())).to.equals(10)
        })
    
    })
    

    执行测试命令

    npx hardhat test
    

    出现如下图,说明编写合约已成功


    image.png

    编译成功的 abi 资源将在 abi 文件夹显示

    image.png

    在 bscnet(币安智能链测试网) 上部署合约

    新建 scripts 存放部署文件

    mkdir scripts
    

    新建 scripts/Demo.ts

    import { ethers } from "hardhat"
    
    async function deploy() {
        const Demo = await ethers.getContractFactory("Demo")
        const demo = await Demo.deploy()
        return await demo.deployed()
    }
    
    async function getNumber(demo) {
        // 合约地址
        console.log("contract address:", demo.address)
        // 调用合约增加 number
        const result = await demo.IncrNumber(10)
        console.log("hash:", result.hash)
    }
    
    deploy().then(getNumber)
    

    执行部署合约命令

    bsctestnet 为 hardhat.config.ts networks数据结构下配置

    npx hardhat run scripts/Demo.ts --network bsctestnet 
    

    部署结果


    image.png

    调用合约设置 number 交易hash:0x8a41057b742ae6b5dbe698656cd07f94e0325c3cdf903cc1825624d509fc08c1


    image.png

    查看当前 number 数值

    进入 hardhat 控制台操作端

    npx hardhat console --network bsctestnet
    

    获取当前 number 数值
    0xAc0857F6C80bCD85493c6d001C49246419810cfF 为合约地址

    > const Demo = await ethers.getContractFactory("Demo");
    undefined
    > const demo = Demo.attach("0xAc0857F6C80bCD85493c6d001C49246419810cfF")
    undefined
    > await demo.GetNumber()
    BigNumber { value: "10" }
    

    如下图所示:结果与预期一致。


    image.png

    相关文章

      网友评论

          本文标题:01 hardhat-初始化第一个合约

          本文链接:https://www.haomeiwen.com/subject/pjepartx.html