web3-multi-provider 2.2.2__tar.gz → 2.2.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: web3-multi-provider
3
- Version: 2.2.2
3
+ Version: 2.2.6
4
4
  Summary: Web3py provider that makes it easy to switch between different blockchain nodes to make sure application will be be online if main blockchain node will be unavailable.
5
5
  License: MIT
6
6
  Author: Raman
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "web3-multi-provider"
3
- version = "2.2.2"
3
+ version = "2.2.6"
4
4
  description = "Web3py provider that makes it easy to switch between different blockchain nodes to make sure application will be be online if main blockchain node will be unavailable."
5
5
  authors = ["Raman <raman.s@lido.fi>"]
6
6
  license = "MIT License"
@@ -1,5 +1,9 @@
1
1
  from .async_multi_http_provider import AsyncFallbackProvider, AsyncMultiProvider
2
- from .exceptions import NoActiveProviderError, ProtocolNotSupported
2
+ from .exceptions import (
3
+ ChainIdMismatchError,
4
+ NoActiveProviderError,
5
+ ProtocolNotSupported,
6
+ )
3
7
  from .http_session_manager_proxy import HTTPSessionManagerProxy
4
8
  from .metrics import init_metrics
5
9
  from .multi_http_provider import FallbackProvider, MultiProvider
@@ -9,6 +13,7 @@ __all__ = (
9
13
  "MultiProvider",
10
14
  "AsyncFallbackProvider",
11
15
  "AsyncMultiProvider",
16
+ "ChainIdMismatchError",
12
17
  "NoActiveProviderError",
13
18
  "ProtocolNotSupported",
14
19
  "HTTPSessionManagerProxy",
@@ -87,13 +87,10 @@ class AsyncHTTPProviderProxy(AsyncHTTPProvider):
87
87
  int: The current chain ID.
88
88
 
89
89
  Raises:
90
- RuntimeError: If the call to `eth_chainId` fails.
90
+ Exception: If the call to `eth_chainId` fails (any exception from the RPC call).
91
91
  """
92
- try:
93
- resp = await super().make_request(RPCEndpoint("eth_chainId"), [])
94
- return int(resp["result"], 16)
95
- except Exception as e:
96
- raise RuntimeError("Failed to fetch chain ID") from e
92
+ resp = await super().make_request(RPCEndpoint("eth_chainId"), [])
93
+ return int(resp["result"], 16)
97
94
 
98
95
  async def make_batch_request(
99
96
  self, batch_requests: List[Tuple[RPCEndpoint, Any]]
@@ -11,7 +11,11 @@ from web3.providers.rpc.utils import ExceptionRetryConfiguration
11
11
  from web3.types import RPCEndpoint, RPCResponse
12
12
 
13
13
  from web3_multi_provider.async_http_provider_proxy import AsyncHTTPProviderProxy
14
- from web3_multi_provider.exceptions import NoActiveProviderError, ProtocolNotSupported
14
+ from web3_multi_provider.exceptions import (
15
+ ChainIdMismatchError,
16
+ NoActiveProviderError,
17
+ ProtocolNotSupported,
18
+ )
15
19
  from web3_multi_provider.util import sanitize_poa_response
16
20
 
17
21
  logger = logging.getLogger(__name__)
@@ -53,13 +57,42 @@ class AsyncBaseMultiProvider(AsyncJSONBaseProvider, ABC):
53
57
 
54
58
  super().__init__()
55
59
 
60
+ def _validate_chain_ids(self) -> None:
61
+ """
62
+ Validates that all providers have the same chain ID.
63
+
64
+ Raises:
65
+ ChainIdMismatchError: If providers have different chain IDs.
66
+ """
67
+ chain_ids: dict[str, list[str]] = {}
68
+
69
+ for provider in self._providers:
70
+ if hasattr(provider, "_chain_id") and provider._chain_id:
71
+ chain_id = provider._chain_id
72
+ endpoint_uri = str(provider.endpoint_uri)
73
+
74
+ if chain_id not in chain_ids:
75
+ chain_ids[chain_id] = []
76
+ chain_ids[chain_id].append(endpoint_uri)
77
+
78
+ if len(chain_ids) > 1:
79
+ mismatches = []
80
+ for chain_id, endpoints in chain_ids.items():
81
+ mismatches.append(f"Chain ID {chain_id}: {', '.join(endpoints)}")
82
+
83
+ raise ChainIdMismatchError(
84
+ f"Providers have different chain IDs:\n" + "\n".join(mismatches)
85
+ )
86
+
56
87
  async def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
57
- return await self._make_request_with_failover(
88
+ response = await self._make_request_with_failover(
58
89
  method=method,
59
90
  params=params,
60
91
  provider_name=self.__class__.__name__,
61
92
  provider_iter=self.get_providers(),
62
93
  )
94
+ self._validate_chain_ids()
95
+ return response
63
96
 
64
97
  async def _make_request_with_failover(
65
98
  self,
@@ -70,7 +103,7 @@ class AsyncBaseMultiProvider(AsyncJSONBaseProvider, ABC):
70
103
  ) -> RPCResponse:
71
104
  exceptions: list[Exception] = []
72
105
 
73
- for provider in provider_iter:
106
+ for index, provider in enumerate(provider_iter):
74
107
  try:
75
108
  response = await provider.make_request(method, params)
76
109
  except Exception as error: # pylint: disable=broad-except
@@ -78,6 +111,7 @@ class AsyncBaseMultiProvider(AsyncJSONBaseProvider, ABC):
78
111
  logger.warning(
79
112
  {
80
113
  "msg": "Provider not responding.",
114
+ "index": index,
81
115
  "error": str(error).replace(str(provider.endpoint_uri), "****"),
82
116
  }
83
117
  )
@@ -22,3 +22,7 @@ class ProtocolNotSupported(Exception):
22
22
 
23
23
  class ProviderInitialization(Exception):
24
24
  """Error during provider init"""
25
+
26
+
27
+ class ChainIdMismatchError(Exception):
28
+ """Raised when providers in a multi-provider have different chain IDs."""
@@ -1,5 +1,5 @@
1
1
  import logging
2
- from typing import Any, List, Optional, Tuple, Union, cast, override
2
+ from typing import Any, List, Optional, Tuple, Union, cast
3
3
 
4
4
  from eth_typing import URI
5
5
  from web3 import HTTPProvider
@@ -9,7 +9,6 @@ from web3.providers.rpc.utils import ExceptionRetryConfiguration
9
9
  from web3.types import RPCEndpoint, RPCResponse
10
10
 
11
11
  from web3_multi_provider import metrics
12
- from web3_multi_provider.exceptions import ProviderInitialization
13
12
  from web3_multi_provider.http_session_manager_proxy import HTTPSessionManagerProxy
14
13
  from web3_multi_provider.util import normalize_provider
15
14
 
@@ -44,7 +43,7 @@ class HTTPProviderProxy(HTTPProvider):
44
43
  **kwargs: Any,
45
44
  ) -> None:
46
45
  """
47
- Initializes the HTTPProviderProxy instance and fetches the chain ID.
46
+ Initializes the HTTPProviderProxy instance with lazy chain ID fetching.
48
47
 
49
48
  Args:
50
49
  endpoint_uri (Optional[Union[URI, str]]): URI of the Ethereum node.
@@ -64,22 +63,29 @@ class HTTPProviderProxy(HTTPProvider):
64
63
  )
65
64
  self._layer = layer
66
65
  self._uri = normalize_provider(str(self.endpoint_uri))
67
- self._chain_id = ""
68
- self._network = "" # to pass fetching of the chain_id
66
+ self._chain_id: str = ""
67
+ self._network: str = ""
68
+ self._session: Optional[Any] = session
69
+ self._request_session_manager: Optional[HTTPSessionManagerProxy] = None
70
+
71
+ def _ensure_chain_info_initialized(self) -> None:
72
+ """
73
+ Lazily fetches chain ID and maps it to a network name for metric labeling.
74
+ Also sets up the request session manager for batch requests.
75
+ """
76
+ if self._chain_id != "":
77
+ return
69
78
  self._chain_id = str(self._fetch_chain_id())
70
79
  self._network = metrics._CHAIN_ID_TO_NAME.get(int(self._chain_id), "unknown")
71
-
72
- self._request_session_manager: HTTPSessionManagerProxy = (
73
- HTTPSessionManagerProxy(
74
- chain_id=self._chain_id,
75
- uri=self._uri,
76
- network=self._network,
77
- layer=self._layer,
78
- )
80
+ self._request_session_manager = HTTPSessionManagerProxy(
81
+ chain_id=self._chain_id,
82
+ uri=self._uri,
83
+ network=self._network,
84
+ layer=self._layer,
79
85
  )
80
- if session:
86
+ if self._session:
81
87
  self._request_session_manager.cache_and_return_session(
82
- cast(URI, self.endpoint_uri), session
88
+ cast(URI, self.endpoint_uri), self._session
83
89
  )
84
90
 
85
91
  def _fetch_chain_id(self) -> int:
@@ -90,17 +96,22 @@ class HTTPProviderProxy(HTTPProvider):
90
96
  int: The chain ID as an integer.
91
97
 
92
98
  Raises:
93
- ProviderInitialization: If the chain ID could not be retrieved.
99
+ Exception: If the chain ID could not be retrieved (any exception from the RPC call).
100
+ """
101
+ resp = super().make_request(RPCEndpoint("eth_chainId"), [])
102
+ return int(resp["result"], 16)
103
+
104
+ def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
105
+ """
106
+ Makes an RPC request after ensuring chain info is initialized.
94
107
  """
95
- try:
96
- resp = super().make_request(RPCEndpoint("eth_chainId"), [])
97
- return int(resp["result"], 16)
98
- except Exception as e:
99
- raise ProviderInitialization("Failed to fetch chain ID") from e
108
+ self._ensure_chain_info_initialized()
109
+ return super().make_request(method, params)
100
110
 
101
111
  def make_batch_request(
102
112
  self, batch_requests: List[Tuple[RPCEndpoint, Any]]
103
113
  ) -> Union[List[RPCResponse], RPCResponse]:
114
+ self._ensure_chain_info_initialized()
104
115
  self.logger.debug(f"Making batch request HTTP, uri: `{self.endpoint_uri}`")
105
116
  request_data = self.encode_batch_rpc_request(batch_requests)
106
117
  raw_response = self._request_session_manager.make_post_request(
@@ -9,7 +9,11 @@ from web3.providers import JSONBaseProvider
9
9
  from web3.providers.rpc.utils import ExceptionRetryConfiguration
10
10
  from web3.types import RPCEndpoint, RPCResponse
11
11
 
12
- from web3_multi_provider.exceptions import NoActiveProviderError, ProtocolNotSupported
12
+ from web3_multi_provider.exceptions import (
13
+ ChainIdMismatchError,
14
+ NoActiveProviderError,
15
+ ProtocolNotSupported,
16
+ )
13
17
  from web3_multi_provider.http_provider_proxy import HTTPProviderProxy
14
18
  from web3_multi_provider.util import sanitize_poa_response
15
19
 
@@ -54,13 +58,42 @@ class BaseMultiProvider(JSONBaseProvider, ABC):
54
58
 
55
59
  super().__init__()
56
60
 
61
+ def _validate_chain_ids(self) -> None:
62
+ """
63
+ Validates that all providers have the same chain ID.
64
+
65
+ Raises:
66
+ ChainIdMismatchError: If providers have different chain IDs.
67
+ """
68
+ chain_ids: dict[str, list[str]] = {}
69
+
70
+ for provider in self._providers:
71
+ if hasattr(provider, "_chain_id") and provider._chain_id:
72
+ chain_id = provider._chain_id
73
+ endpoint_uri = str(provider.endpoint_uri)
74
+
75
+ if chain_id not in chain_ids:
76
+ chain_ids[chain_id] = []
77
+ chain_ids[chain_id].append(endpoint_uri)
78
+
79
+ if len(chain_ids) > 1:
80
+ mismatches = []
81
+ for chain_id, endpoints in chain_ids.items():
82
+ mismatches.append(f"Chain ID {chain_id}: {', '.join(endpoints)}")
83
+
84
+ raise ChainIdMismatchError(
85
+ f"Providers have different chain IDs:\n" + "\n".join(mismatches)
86
+ )
87
+
57
88
  def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
58
- return self._make_request_with_failover(
89
+ response = self._make_request_with_failover(
59
90
  method=method,
60
91
  params=params,
61
92
  provider_name=self.__class__.__name__,
62
93
  provider_iter=self.get_providers(),
63
94
  )
95
+ self._validate_chain_ids()
96
+ return response
64
97
 
65
98
  @staticmethod
66
99
  def _make_request_with_failover(
@@ -71,7 +104,7 @@ class BaseMultiProvider(JSONBaseProvider, ABC):
71
104
  ) -> RPCResponse:
72
105
  exceptions: list[Exception] = []
73
106
 
74
- for provider in provider_iter:
107
+ for index, provider in enumerate(provider_iter):
75
108
  try:
76
109
  response = provider.make_request(method, params)
77
110
  except Exception as error: # pylint: disable=broad-except
@@ -79,6 +112,7 @@ class BaseMultiProvider(JSONBaseProvider, ABC):
79
112
  logger.warning(
80
113
  {
81
114
  "msg": "Provider not responding.",
115
+ "index": index,
82
116
  "error": str(error).replace(str(provider.endpoint_uri), "****"),
83
117
  }
84
118
  )