Skip to content

Commit 70ba9be

Browse files
committed
refactor: centralize hardhat configuration
1 parent 4e786d6 commit 70ba9be

9 files changed

Lines changed: 62 additions & 38 deletions

File tree

backend/config/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
"""Configuration package for backend services."""

backend/config/hardhat_config.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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))

backend/database_handler/transactions_processor.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
import time
1616
from backend.domain.types import TransactionType
1717
from web3 import Web3
18-
import os
18+
from backend.config.hardhat_config import HardhatConfig
1919

2020

2121
class 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:

backend/protocol_rpc/endpoint_generator.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,10 @@
1111
from flask_jsonrpc.exceptions import JSONRPCError
1212
from functools import partial, wraps
1313
import requests
14-
import os
1514
import traceback
1615
from backend.protocol_rpc.aio import run_in_main_server_loop
1716
from backend.protocol_rpc.message_handler.base import MessageHandler
17+
from backend.config.hardhat_config import HardhatConfig
1818

1919

2020
def get_json_rpc_method_name(function: Callable, method_name: str | None = None):
@@ -67,9 +67,7 @@ def unfold(x: typing.Any):
6767
def 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()

backend/rollup/consensus_service.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
import json
2-
import os
3-
from web3 import Web3
42
from typing import Optional, Dict, Any
53
from pathlib import Path
64
from hexbytes import HexBytes
@@ -9,6 +7,7 @@
97
from backend.rollup.default_contracts.consensus_main import (
108
get_default_consensus_main_contract,
119
)
10+
from backend.config.hardhat_config import HardhatConfig
1211

1312

1413
class 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

tests/db-sqlalchemy/conftest.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
import os
22
from typing import Iterable
3+
from unittest.mock import patch, MagicMock
34

45
import pytest
56
from sqlalchemy import Engine, create_engine
67
from sqlalchemy.orm import Session, sessionmaker
8+
from web3 import Web3
9+
from web3.providers import BaseProvider
710

811
from backend.database_handler.models import Base
912
from backend.database_handler.transactions_processor import TransactionsProcessor
@@ -41,4 +44,15 @@ def session(engine: Engine) -> Iterable[Session]:
4144

4245
@pytest.fixture
4346
def 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)

tests/db-sqlalchemy/transactions_processor_test.py

Lines changed: 4 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,24 @@
1-
from sqlalchemy.orm import Session
21
import pytest
3-
from unittest.mock import patch, MagicMock
2+
from unittest.mock import patch
43
import os
54
import math
65
from 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
127
from backend.database_handler.transactions_processor import TransactionStatus
138
from 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

3624
def test_transactions_processor(transactions_processor: TransactionsProcessor):

tests/hardhat/docker-compose.yml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff 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

tests/hardhat/test_hardhat.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
1-
from web3 import Web3
21
import json
32
from eth_account import Account
4-
import os
3+
from backend.config.hardhat_config import HardhatConfig
54

65

76
def 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():

0 commit comments

Comments
 (0)