1
0

More than 1 year has passed since last update.

web3.pyでhardhat_resetを実行する方法

Last updated at Posted at 2022-01-06

hardhatのethノードでは、hardhat_resetなどの特殊なコマンドが使える。web3.pyでそのコマンドを使う方法を紹介する

hardhat用のモジュール

web3.pyはモジュールで機能を拡張できる。w3.ethなどもモジュールとして実装されている。w3.ethの実装を参考に以下のように書いたら、hardhatコマンドを使えるようになった。

# license: CC0
from web3.module import Module, Method
from web3.types import RPCEndpoint

class HardhatModule(Module):

    def reset(self):
        return self._hardhat_reset()

    _hardhat_reset = Method(RPCEndpoint("hardhat_reset"))

hardhat用のモジュールの使い方

w3にモジュールをattach_modulesで注入する。

# license: CC0
import os
from unittest import TestCase
from web3 import Web3
from web3._utils.module import attach_modules
from src.hardhat_module import HardhatModule


class TestHardhatModuleReset(TestCase):
    def test_reset(self):
        external_modules = {
            'hardhat': (HardhatModule, )
        }
        w3 = Web3(Web3.HTTPProvider(os.getenv('WEB3_PROVIDER_URI')))
        attach_modules(w3, external_modules)

        w3.hardhat.reset()

v5.25.0には含まれていないが、masterにあるexternal_modules

以下のPRでexternal_modulesが追加されて、実装詳細(from web3._utils.module import attach_modules)に依存しなくてよくなったらしい。まだ、pipの最新版(v5.25.0)には含まれていないらしい。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0