File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ """Configuration package for backend services."""
Original file line number Diff line number Diff line change 1+ """Centralized configuration for Hardhat settings."""
2+
3+ import os
4+ from web3 import Web3
5+
6+
7+ class HardhatConfig :
8+ """Configuration class for Hardhat network settings."""
9+
10+ @staticmethod
11+ def get_port () -> str :
12+ """Get the Hardhat port from environment variable."""
13+ return os .environ .get ("HARDHAT_PORT" , "8545" )
14+
15+ @staticmethod
16+ def get_base_url () -> str :
17+ """Get the Hardhat base URL from environment variable."""
18+ return os .environ .get ("HARDHAT_URL" , "http://localhost" )
19+
20+ @staticmethod
21+ def get_full_url () -> str :
22+ """Get the complete Hardhat URL with port."""
23+ port = HardhatConfig .get_port ()
24+ url = HardhatConfig .get_base_url ()
25+ return f"{ url } :{ port } "
26+
27+ @staticmethod
28+ def get_web3_instance () -> Web3 :
29+ """Get a Web3 instance connected to Hardhat network."""
30+ hardhat_url = HardhatConfig .get_full_url ()
31+ return Web3 (Web3 .HTTPProvider (hardhat_url ))
Original file line number Diff line number Diff line change 1515import time
1616from backend .domain .types import TransactionType
1717from web3 import Web3
18- import os
18+ from backend . config . hardhat_config import HardhatConfig
1919
2020
2121class TransactionAddressFilter (Enum ):
@@ -105,10 +105,7 @@ def __init__(
105105 self .session = session
106106
107107 # Connect to Hardhat Network
108- port = os .environ .get ("HARDHAT_PORT" )
109- url = os .environ .get ("HARDHAT_URL" )
110- hardhat_url = f"{ url } :{ port } "
111- self .web3 = Web3 (Web3 .HTTPProvider (hardhat_url ))
108+ self .web3 = HardhatConfig .get_web3_instance ()
112109
113110 @staticmethod
114111 def _parse_transaction_data (transaction_data : Transactions ) -> dict :
Original file line number Diff line number Diff line change 1111from flask_jsonrpc .exceptions import JSONRPCError
1212from functools import partial , wraps
1313import requests
14- import os
1514import traceback
1615from backend .protocol_rpc .aio import run_in_main_server_loop
1716from backend .protocol_rpc .message_handler .base import MessageHandler
17+ from backend .config .hardhat_config import HardhatConfig
1818
1919
2020def get_json_rpc_method_name (function : Callable , method_name : str | None = None ):
@@ -67,9 +67,7 @@ def unfold(x: typing.Any):
6767def setup_eth_method_handler (jsonrpc : JSONRPC ):
6868 """Forwards eth_ methods to Hardhat if no own implementation is available"""
6969 app = jsonrpc .app
70- port = os .environ .get ("HARDHAT_PORT" )
71- url = os .environ .get ("HARDHAT_URL" )
72- HARDHAT_URL = f"{ url } :{ port } "
70+ hardhat_url = HardhatConfig .get_full_url ()
7371
7472 @app .before_request
7573 def handle_eth_methods ():
@@ -89,7 +87,7 @@ def handle_eth_methods():
8987 try :
9088 with requests .Session () as http :
9189 result = http .post (
92- HARDHAT_URL ,
90+ hardhat_url ,
9391 json = request_json ,
9492 headers = {"Content-Type" : "application/json" },
9593 ).json ()
Original file line number Diff line number Diff line change 11import json
2- import os
3- from web3 import Web3
42from typing import Optional , Dict , Any
53from pathlib import Path
64from hexbytes import HexBytes
97from backend .rollup .default_contracts .consensus_main import (
108 get_default_consensus_main_contract ,
119)
10+ from backend .config .hardhat_config import HardhatConfig
1211
1312
1413class ConsensusService :
@@ -17,10 +16,7 @@ def __init__(self):
1716 Initialize the ConsensusService class
1817 """
1918 # Connect to Hardhat Network
20- port = os .environ .get ("HARDHAT_PORT" )
21- url = os .environ .get ("HARDHAT_URL" )
22- hardhat_url = f"{ url } :{ port } "
23- self .web3 = Web3 (Web3 .HTTPProvider (hardhat_url ))
19+ self .web3 = HardhatConfig .get_web3_instance ()
2420
2521 self .web3_connected = self .web3 .is_connected ()
2622
Original file line number Diff line number Diff line change 11import os
22from typing import Iterable
3+ from unittest .mock import patch , MagicMock
34
45import pytest
56from sqlalchemy import Engine , create_engine
67from sqlalchemy .orm import Session , sessionmaker
8+ from web3 import Web3
9+ from web3 .providers import BaseProvider
710
811from backend .database_handler .models import Base
912from backend .database_handler .transactions_processor import TransactionsProcessor
@@ -41,4 +44,15 @@ def session(engine: Engine) -> Iterable[Session]:
4144
4245@pytest .fixture
4346def transactions_processor (session : Session ) -> Iterable [TransactionsProcessor ]:
44- yield TransactionsProcessor (session )
47+ # Create a mock Web3 instance with proper provider
48+ mock_provider = MagicMock (spec = BaseProvider )
49+ web3_instance = Web3 (mock_provider )
50+ web3_instance .eth = MagicMock ()
51+ web3_instance .eth .accounts = ["0x0000000000000000000000000000000000000000" ]
52+
53+ # Patch HardhatConfig.get_web3_instance to return our mock
54+ with patch (
55+ "backend.database_handler.transactions_processor.HardhatConfig.get_web3_instance" ,
56+ return_value = web3_instance ,
57+ ):
58+ yield TransactionsProcessor (session )
Original file line number Diff line number Diff line change 1- from sqlalchemy .orm import Session
21import pytest
3- from unittest .mock import patch , MagicMock
2+ from unittest .mock import patch
43import os
54import math
65from datetime import datetime
7- from web3 import Web3
8- from web3 .providers import BaseProvider
96
10- from backend .database_handler .chain_snapshot import ChainSnapshot
11- from backend .database_handler .models import Transactions
127from backend .database_handler .transactions_processor import TransactionStatus
138from backend .database_handler .transactions_processor import TransactionsProcessor
149
1510
1611@pytest .fixture (autouse = True )
17- def mock_env_and_web3 ():
12+ def mock_env ():
1813 with patch .dict (
1914 os .environ ,
2015 {
2116 "HARDHAT_PORT" : "8545" ,
2217 "HARDHAT_URL" : "http://localhost" ,
2318 "HARDHAT_PRIVATE_KEY" : "0x0123456789" ,
2419 },
25- ), patch ("web3.Web3.HTTPProvider" ):
26- web3_instance = Web3 (MagicMock (spec = BaseProvider ))
27- web3_instance .eth = MagicMock ()
28- web3_instance .eth .accounts = ["0x0000000000000000000000000000000000000000" ]
29- with patch (
30- "backend.database_handler.transactions_processor.Web3" ,
31- return_value = web3_instance ,
32- ):
33- yield
20+ ):
21+ yield
3422
3523
3624def test_transactions_processor (transactions_processor : TransactionsProcessor ):
Original file line number Diff line number Diff line change @@ -30,4 +30,5 @@ services:
3030 hardhat :
3131 condition : service_healthy
3232 environment :
33- - HARDHAT_URL=http://hardhat:8545
33+ - HARDHAT_URL=http://hardhat
34+ - HARDHAT_PORT=8545
Original file line number Diff line number Diff line change 1- from web3 import Web3
21import json
32from eth_account import Account
4- import os
3+ from backend . config . hardhat_config import HardhatConfig
54
65
76def test_eth_account ():
@@ -41,8 +40,7 @@ def connect_to_hardhat():
4140 Raises:
4241 Exception: If the connection to the Hardhat network fails.
4342 """
44- hardhat_url = os .environ .get ("HARDHAT_URL" )
45- web3 = Web3 (Web3 .HTTPProvider (hardhat_url ))
43+ web3 = HardhatConfig .get_web3_instance ()
4644
4745 # Check connection
4846 if not web3 .is_connected ():
You can’t perform that action at this time.
0 commit comments