Hardhat.

김진경·2022년 5월 4일
0

Dapp

목록 보기
1/2

공식 홈페이지
https://hardhat.org/getting-started/#installation


hardhat 명령어.

hardhat 설치.

$ npm install --save-dev hardhat

hardhat 최초 디렉토리 설정.

$ npx hardhat
// npx hardhat 명령어는 최초 디렉토리 설정 이후 한번 더 실행할 경우, hardhat 명령어를 띄우게 된다.

컨트랙트 컴파일하기

$ npx hardhat compile
// 컴파일할 컨트랙트 파일을 'contracts' 폴더에서 찾아 컴파일한다.

컨트랙트 테스트하기

$ npx hardhat test

hardhat 네트워크 실행

$ npx hardhat node
//hardhat 네트워크는, hardhat 패키지에 내장된 가상 블록체인에 대응하여 테스트를 할 수 있도록 내장 기능이다.



hardhat 소스 분석.

artifacts 디렉토리

컴파일할 컨트랙트 파일을 'contracts' 폴더에서 찾고, 컴파일 된 코드는 'artifacts'폴더에 생성된다.


hardhat.config.js

hardhat으로 할 수 있는 실행문을 저장한 파일이다.
ex) $ npx hardhat accounts - hardhat 네트워크의 어카운트 목록을 보여준다.

task("accounts", "Prints the list of accounts", async (taskArgs, hre) => {
  const accounts = await hre.ethers.getSigners();

  for (const account of accounts) {
    console.log(account.address);
  }
});

실행 결과.


sample-test.js

hardhat으로 테스트를 담당하는 파일이다.
ex) $ npx hardhat test

// sample-test.js
describe("Greeter", function () {
  it("Should return the new greeting once it's changed", async function () {
    const Greeter = await ethers.getContractFactory("Greeter");
    const greeter = await Greeter.deploy("Hello, world!");
    await greeter.deployed();

    expect(await greeter.greet()).to.equal("Hello, world!");

    const setGreetingTx = await greeter.setGreeting("Hola, mundo!");

    // wait until the transaction is mined
    await setGreetingTx.wait();

    expect(await greeter.greet()).to.equal("Hola, mundo!");
  });
});
// Greeter.sol
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;

import "hardhat/console.sol";

contract Greeter {
    string private greeting;

    constructor(string memory _greeting) {
        console.log("Deploying a Greeter with greeting:", _greeting);
        greeting = _greeting;
    }

    function greet() public view returns (string memory) {
        return greeting;
    }

    function setGreeting(string memory _greeting) public {
        console.log("Changing greeting from '%s' to '%s'", greeting, _greeting);
        greeting = _greeting;
    }
}

실행결과



hardhat forking

이더리움 메인넷 컨트랙트를 hardhat 네트워크에서 돌아갈 수 있도록 포킹한다. forking으로 테스트를 하기 위해선 hardhat.config.js에서 설정이 필요하다.

// hardhat.config.js
module.exports = {
  solidity: "0.8.4",
  networks : {
    hardhat : {
      forking : {
        url: "https://eth-mainnet.alchemyapi.io/v2/<key>"
        // <key> 부분에 api key를 넣어야 한다.
      }
    }
  }
};

실행 결과 :

➜  hardhat_test_practice git:(master) ✗ npx hardhat test
You're running a network fork starting from the latest block.
Performance may degrade due to fetching data from the network with each run.
If connecting to an archival node (e.g. Alchemy), we strongly recommend setting
blockNumber to a fixed value to increase performance with a local cache.

위 문단이 나오고 테스트 결과가 나온다.


Shorthand and autocomplete

hardhat에서 제공하는 단축 명령어, 자동완성 기능이다.
설치

$ npm i -g hardhat-shorthand

컨트랙트 테스트

$ hh test
profile
Maktub.

0개의 댓글