Open4

Tips for Hardhat

Task

Return Value

  • task で return をすれば、呼び出し側で受け取ることができる
    • return value は type Object も可能
tasks/child-task.ts
task("child-task").setAction(async ({}, hre) => {
  return {
    first: "a",
    second: "b",
    third: "c"
  }
})
tasks/parent-task.ts
task("parent-task").setAction(async ({}, hre) => {
  const values = await hre.run(`child-task`)
  console.log(values)
})

// {
//  first: "a",
//  second: "b",
//  third: "c"
// }

Ethers.js

https://hardhat.org/plugins/nomiclabs-hardhat-ethers.html
scripts/sample.ts
import hh from "hardhat"
import { Xxx__factory } from "../typechain"

const main = async () => {
  const { network, ethers } = hh

  // get network name
  console.log(network.name) // ex: rinkeby

  // get Signer
  const [signer] = await ethers.getSigners() // SignerWithAddress (extended definition by hardhat-ethers)
  console.log(signer.address) // ex: 0x...

  // connect Contract
  const instance = Xxx__factory.connect(adrs.Booster, ethers.provider) // without signer
  // const instance = Xxx__factory.connect(adrs.Booster, signer) // with signer
  console.log(await instance.symbol()) // ex: XYZ
}

main().catch((e) => {
  console.error(e);
  process.exitCode = 1;
});

Configuration

ガス不足の場合

hardhat (hardhat.config.ts)

ethers.js (& typechain)

  • gasLimit をセットして上限を上げる
    • await myContract.connect(signer).estimateGas.sample(weights, { gasLimit: N })

(test の場合)

  • そういったヘビーな function の確認は mocha が timeout しがちなので、timeout を設定する
    • it(test, async () => { ... }).timeout(300 * 1000)

etherjs で実際の network で実行した場合下記のエラーが出るようなケース

Error: cannot estimate gas; transaction may fail or may require manual gas limit
...
  reason: 'cannot estimate gas; transaction may fail or may require manual gas limit',
  code: 'UNPREDICTABLE_GAS_LIMIT',
  error: ProviderError: gas required exceeds allowance 15000000
  ...
  method: 'estimateGas',
  ...

hardhat test では下記のようなエラーが出ていた

     Error: Transaction reverted and Hardhat couldn't infer the reason. Please report this to help us improve Hardhat.
      at MyContract._sample (contracts/MyContract.sol:258)
      at MyContract.sample (contracts/MyContract.sol:286)
      at <UnrecognizedContract>.<unknown> (0xcc4c41415fc68b2fbf70102742a83cde435e0ca7)
      at async EthModule._estimateGasAction (node_modules/hardhat/src/internal/hardhat-network/provider/modules/eth.ts:429:7)
      at async HardhatNetworkProvider.request (node_modules/hardhat/src/internal/hardhat-network/provider/provider.ts:118:18)
      at async EthersProviderWrapper.send (node_modules/hardhat-deploy-ethers/src/internal/ethers-provider-wrapper.ts:13:20)
ログインするとコメントできます