在本机部署HelloWorld智能合约

301 阅读2分钟

在本机部署HelloWorld智能合约

初始化

初始化环境

# jpegdegenns为自定义名称,可以改变
mkdir jpegdegenns
cd jpegdegenns
git init
yarn init -y
yarn add hardhat -d
npx hardhat

在执行npx hardhat后弹出如下选项:

step1-1.png

选最后一个,自动创建hardhat配置文件

项目文件结构

jpegdegens
    - contracts
        - YourContracts.sol
    ...
    - scripts
        - deploy.ts
        ...
    - test
        - sometest.js
        ...

打开.sol文件,编辑合约内容:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
​
contract HelloWorld {
    function hello() public pure returns (string memory){
        return "Hello, World";
    }
}

编译:npx hardhat compile,生成artifacts文件夹

测试

测试环境搭建

运行如下命令:

npm install --save-dev @nomiclabs/hardhat-ethers ethers @nomiclabs/hardhat-waffle ethereum-waffle chai
​
npm install typescript ts-node -d
​
npm install -d chai @types/node @types/mocha @types/chai

hardhat.config.js改名为hardhat.config.ts

在hardhat.config.ts中头部添加如下两行,让vscode能对类型做出正确的推断:

import "@nomiclabs/hardhat-waffle"
import "@nomiclabs/hardhat-ethers"

创建测试文件:./test/HelloWorld.ts

import "@nomiclabs/hardhat-ethers"
import { ethers } from "hardhat"
import {expect} from "chai"describe("hello world", function(){
    it("should say hi", async function(){
        // deploy our contract
        const HelloWorld = await ethers.getContractFactory("HelloWorld")
        const hello = await HelloWorld.deploy()
        await hello.deployed()
​
        expect(await hello.hello()).to.equal("Hello, World")
    })
})

运行测试命令:npx hardhat test

step1-2.png

测试通过

部署

编写部署文件./scripts/deploy-hello.ts:

import "@nomiclabs/hardhat-ethers"
import {ethers} from "hardhat"async function deploy(){
    const HelloWorld = await ethers.getContractFactory("HelloWorld")
    const hello = await HelloWorld.deploy()
    await hello.deployed()
​
    return hello
}
​
// @ts-ignore
async function sayHello(hello){
    console.log("Say Hello", await hello.hello())
}
​
deploy().then(sayHello)

这里实际上是在做和测试阶段一样的事。

我们要使用rpc将我们的协约传送到某个网络上,然后协约在网络间进行转发,当转发达到一定次数,则认为协议已经被部署了。

下面我们在本地创建网络:

npx hardhat node

这条命令会在本机上部署一个以太坊网络,从而可以让我们部署自己的协约。

step1-3.png

可以看到,已经有几个账户被创建好了,且每个账户都有10000eth。记当前终端为终端1。

部署协约:

新建一个终端,运行npx hardhat run scripts/deploy-hello.ts --network localhost,部署成功后输出下面文字。

step1-4.png

与此同时,终端1输出如下内容:

step1-5.png

可以看到本机网络中已经发生了交易。Contract deployment: HelloWorld就是我们刚刚部署的协议。从From字段的值与之前账户号对应,可以看出,第一个测试账户被用于支付部署的费用。

由此我们成功部署了HelloWorld协约。