Now and Nawoo

NFTの制作記録、技術メモ → C#, Solidity, Blockchain, Bitcoin, Ethereum, NFT

Hardhatの使い方メモ (1) セットアップ~コンパイル

Solidityの開発環境 Hardhat を試してみました。

実行環境は Windows10, VSCode, Node.js 14.17.6 です。

インストール

必要なパッケージが多いので、まとめてインストールしておきます。

> cd my-project
> npm init -y
> npm i -D hardhat @nomiclabs/hardhat-waffle ethereum-waffle chai @nomiclabs/hardhat-ethers ethers
> npm i -D @nomiclabs/hardhat-etherscan  # ← Etherscan/PolygonscanにVerityするなら必要
> npx hardhat

secrets.jsonを作成

Ethereumメインネットやテストネットにデプロイするなら、InfuraAlchemy に登録してAPI KEYを取得しておきます。 今回はAlchemyを使ってみました。

{
  "mnemonic": "~",
  "polygonscanApiKey": "~", // PolygonscanでVerifyする場合
  "etherscanApiKey": "~",  // EtherscanでVerifyする場合
  "alchemyApiKey": "~"  // Ethereumのメインネットやテストネットを使う場合
}

hardhat.config.jsを編集

hardhat.config.jsではコンパイラの設定(バージョンや最適化の有無)、ネットワークの設定、Verify用のAPI KEYの設定をします。 ネットワークは Rinkeby、Polygonメインネット、Polygonテストネットを追加しておきました。

タスクの登録もできますが、私は使っていません。

const { mnemonic, polygonscanApiKey, etherscanApiKey, alchemyApiKey } = require("./secrets.json");

require("@nomiclabs/hardhat-waffle");
require('@nomiclabs/hardhat-ethers');
require("@nomiclabs/hardhat-etherscan");

// 中略 (Task関連)

module.exports = {
  solidity: {
    version: "0.8.7",
    settings: {
      optimizer: {
        enabled: true,
        runs: 200
      }
    }
  },
  networks: {
    hardhat: {},
    rinkeby: {
      url: "https://eth-rinkeby.alchemyapi.io/v2/" + alchemyApiKey,
      chainId: 4,
      accounts: { mnemonic },
    },
    matic_mainnet: {
      url: "https://matic-mainnet.chainstacklabs.com",
      chainId: 137,
      accounts: { mnemonic }
    },
    matic_testnet: {
      url: "https://matic-mumbai.chainstacklabs.com",
      chainId: 80001,
      accounts: { mnemonic }
    }
  },
  etherscan: {
    // apiKey: etherscanApiKey    // EtherscanでVerifyする場合
    apiKey: polygonscanApiKey    // PolygonscanでVerifyする場合
  }
};

コンパイル

> npx hardhat compile

作成されたartifactsを削除するには

> npx hardhat clean

テスト

> npx hardhat test

testディレクトリ内のテストを実行します。 あまりテスト書かないので、特にコメントがない、、、(^^;

Solidityファイル内でconsole.log

Hardhatでは、Solidity(*.sol)ファイル内でconsole.logが使えます。

Debugging with Hardhat Network | Hardhat

//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;

import "hardhat/console.sol";  // ←ここでimport

contract Test {
    function testFunc(uint256 value) public view {
        console.log("testFunc", value); // ←関数内でconsole.logが使える
    }
}

test、script、consoleなどで関数を呼び出したときに、ターミナルにconsole.logの内容が表示されるので、デバッグに便利です。 ただ、テストの結果にconsole.logの出力が混ざってしまうので見づらくなります。

 

次回はデプロイ&Verify編です。(長くなったので分けました。)