Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added check for block timestamp #3

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions web3/providers/rpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from requests import (
RequestException,
)
from datetime import datetime
from typing import (
Any,
Dict,
Expand Down Expand Up @@ -64,6 +65,7 @@ def __init__(
randomize: Optional[bool] = False,
request_kwargs: Optional[Any] = None,
session: Optional[Any] = None,
block_timeout_sec: Optional[int] = None,
) -> None:
if isinstance(providers, str):
providers = [
Expand All @@ -72,6 +74,7 @@ def __init__(
self.randomize = randomize
self.providers = providers
self._request_kwargs = request_kwargs or {}
self.block_timeout_sec = block_timeout_sec

if session:
cache_session(self.providers[0], session)
Expand Down Expand Up @@ -104,6 +107,23 @@ def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
"Making request HTTP. URI: %s, Method: %s", provider_uri, method
)
try:
if self.block_timeout_sec:
request_data_for_block = self.encode_rpc_request(
"eth_getBlockByNumber", ("latest", False)
)
raw_response = make_post_request(
provider_uri,
request_data_for_block,
**self.get_request_kwargs()
)
response = self.decode_rpc_response(raw_response)
last_block_timestamp = int(
response.get("result").get("timestamp"), base=16
)
now_timestamp = datetime.now().timestamp()
if now_timestamp - last_block_timestamp > self.block_timeout_sec:
continue

raw_response = make_post_request(
provider_uri, request_data, **self.get_request_kwargs()
)
Expand Down