provider.fallback
Documentation for eth_defi.provider.fallback Python module.
JSON-RPC provider fallback and redundancy mechanisms.
See
FallbackProvider
Functions
|
Get the fallback provider of a Wen3 instance. |
Classes
Fault-tolerance for JSON-RPC requests with multiple providers. |
|
Different supported fallback strategies. |
Exceptions
Raised when a fallback provider returns a different chain ID after switching. |
|
A ValueError that is used to signal that the RPC response was not valid. |
|
Raised when a provider cannot answer chain ID verification. |
- exception ChainIdMismatch
Bases:
ExceptionRaised when a fallback provider returns a different chain ID after switching.
This typically happens when an RPC endpoint is misconfigured or its backend temporarily routes requests to the wrong chain after an outage.
- __init__(*args, **kwargs)
- __new__(**kwargs)
- add_note(note, /)
Add a note to the exception
- with_traceback(tb, /)
Set self.__traceback__ to tb and return self.
- exception ExtraValueError
Bases:
ValueErrorA ValueError that is used to signal that the RPC response was not valid.
Add extra debugging.
- __init__(*args, **kwargs)
- __new__(**kwargs)
- add_note(note, /)
Add a note to the exception
- with_traceback(tb, /)
Set self.__traceback__ to tb and return self.
- class FallbackProvider
Bases:
eth_defi.provider.named.BaseNamedProviderFault-tolerance for JSON-RPC requests with multiple providers.
Fall back to the next provider on the list if a JSON-RPC request fails. Contains build-in retry logic in round-robin manner. We will also recover from situations when we suspect the node does not have the block data we are asking yet (but should have shorty).
See also
eth_defi.middlware.exception_retry_middleware()eth_defi.middlware.ProbablyNodeHasNoBlock()
Note
FallbackProviderdoes not call any middlewares installed on the providers themselves.- Parameters
providers – List of provider we cycle through.
strategy –
What is the strategy to deal with errors.
Currently on cycling supported.
retryable_exceptions – List of exceptions we can retry.
retryable_status_codes – List of HTTP status codes we can retry.
retryable_rpc_error_codes – List of GoEthereum error codes we can retry.
sleep – Seconds between retries.
backoff – Multiplier to increase sleep.
retries – How many retries we attempt before giving up.
switchover_noisiness – How loud we are about switchover issues.
state_missing_switch_over_delay –
If we encounter state missing condition at node, what is the minimum time (seconds) we wait before trying to switch to next node.
See code comments for details.
- __init__(providers, strategy=FallbackStrategy.cycle_on_error, retryable_exceptions=(<class 'requests.exceptions.ConnectionError'>, <class 'requests.exceptions.HTTPError'>, <class 'requests.exceptions.Timeout'>, <class 'requests.exceptions.TooManyRedirects'>, <class 'web3.exceptions.BlockNotFound'>, <class 'requests.exceptions.ChunkedEncodingError'>, <class 'http.client.RemoteDisconnected'>, <class 'eth_defi.middleware.SomeCrappyRPCProviderException'>, <class 'requests.exceptions.ContentDecodingError'>), retryable_status_codes=(429, 500, 502, 503, 504, 525, 520, 410, 403, 400, 401), retryable_rpc_error_codes=(-32003, -32043, -32005, -32701, 42903, -32002, -32603, -32052, -32601), sleep=5.0, backoff=1.6, retries=6, state_missing_switch_over_delay=12.0, switchover_noisiness=30)
- Parameters
providers (list[eth_defi.provider.named.BaseNamedProvider | web3.providers.rpc.rpc.HTTPProvider]) – List of provider we cycle through.
strategy –
What is the strategy to deal with errors.
Currently on cycling supported.
retryable_exceptions – List of exceptions we can retry.
retryable_status_codes – List of HTTP status codes we can retry.
retryable_rpc_error_codes – List of GoEthereum error codes we can retry.
sleep (float) – Seconds between retries.
backoff (float) – Multiplier to increase sleep.
retries (int) – How many retries we attempt before giving up.
switchover_noisiness – How loud we are about switchover issues.
state_missing_switch_over_delay (float) –
If we encounter state missing condition at node, what is the minimum time (seconds) we wait before trying to switch to next node.
See code comments for details.
- property call_endpoint_uri: str
Return the active node URI where call JSON-RPCs go.
Warning
Endpoint URIs often contain API keys. They should be never publicly displayed as is.
- property endpoint_uri
Return the active node URI endpoint.
For
HTTPProvidercompatibility.
- get_active_provider()
Get currently active provider.
If this provider fails, we are automatically recycled to the next one.
- Return type
Union[eth_defi.provider.named.BaseNamedProvider, web3.providers.rpc.rpc.HTTPProvider]
- get_provider_context_for_log(provider)
Get provider diagnostics suitable for warning logs.
The context includes Anvil launch metadata when the local Anvil provider has metadata copied by
create_multi_provider_web3(). The metadata is registered byeth_defi.provider.anvil.launch_anvil(). Upstream RPC URLs are reduced to domains to avoid leaking API keys.- Parameters
provider (Union[eth_defi.provider.named.BaseNamedProvider, web3.providers.rpc.rpc.HTTPProvider]) – Provider that handled the failing JSON-RPC request.
- Returns
Dictionary safe to include in logs.
- Return type
- make_request(method, params)
Make a request.
By default use the current active provider
If there are errors try cycle through providers and sleep between cycles until one provider works
Use a special “ignore_error” parameter to skip retries, if given in
eth_callpayload.
- Parameters
method (web3.types.RPCEndpoint) –
params (Any) –
- Return type
web3.types.RPCResponse
- request_func(w3, middleware_onion)
@param w3 is the web3 instance @param middleware_onion is an iterable of middleware,
ordered by first to execute
- @returns a function that calls all the middleware and
eventually self.make_request()
- reset_switch()
Reset the provider switch to the first provider.
Assume we have main provider and more expensive backup providers
Try to switch back to the main provider if we have switched away due to a temporary error
Used in batch scan tasks
- switch_provider(log_level=None, randomise=False, cause='<not specified>')
Switch to next available provider.
After switching, verifies that the new provider returns the same
eth_chainIdas the previously observed value. Providers that cannot answer the verification call are skipped when other alternatives are available. Providers that answer with a different chain ID are rejected.
- switch_to_provider_index(new_index, log_level=None, cause='<not specified>')
Switch to a specific provider by index, with the same verification as
switch_provider().Use this when you need to deterministically select one upstream (e.g. to fail a chain over to a known-good single node) rather than cycling or randomising. Like
switch_provider(), after switching it verifies the new provider returns the expectedeth_chainIdand rolls back to the previous provider (raisingChainIdMismatch) if it does not, so a misconfigured or mis-routing endpoint cannot be silently selected.- Parameters
- Raises
ChainIdMismatch – If the new provider reports a different chain ID than expected.
ProviderNotAvailable – If the new provider cannot answer
eth_chainIdverification.
- verify_providers()
Check that all providers return the same chain ID.
Call this at startup to detect misconfigured RPC endpoints before any trading logic runs. Providers that do not answer during startup are left in the fallback rotation, because their availability can be transient and runtime switching verifies chain ID before selecting them.
- Raises
ChainIdMismatch – If responding providers return different chain IDs, or if no provider can be reached at all.
- exception ProviderNotAvailable
Bases:
eth_defi.provider.fallback.ChainIdMismatchRaised when a provider cannot answer chain ID verification.
This is a recoverable switchover condition when other fallback providers are available. It subclasses
ChainIdMismatchfor backwards compatibility with callers that treat failed chain ID verification as a rejected provider selection.- __init__(*args, **kwargs)
- __new__(**kwargs)
- add_note(note, /)
Add a note to the exception
- with_traceback(tb, /)
Set self.__traceback__ to tb and return self.
- get_fallback_provider(web3)
Get the fallback provider of a Wen3 instance.
Can be nested in
eth_defi.provider.mev_block.MEVBlockerProvider.- Parameters
web3 (web3.main.Web3) – Web3 instance
- Raises
AssertionError – If there is no fallback provider available
- Return type