-
Notifications
You must be signed in to change notification settings - Fork 0
etherscan v2 multichain api #113
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
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
3bee58c
etherscan class, new get_block_by_timestamp method
jalbrekt85 209f41b
style: ci lint with `black`
jalbrekt85 4dd2cf4
update class name
jalbrekt85 7faf01b
add etherscan env var
jalbrekt85 d9db9fe
remove outdated fetch block mock test
jalbrekt85 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| ETHNODEURL= | ||
| DRPC_KEY= | ||
| GRAPH_API_KEY= | ||
| ETHERSCAN_API_KEY= |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| import os | ||
| import time | ||
| from typing import Optional, Dict, Any | ||
| import requests | ||
| from requests.adapters import HTTPAdapter | ||
| from urllib3.util.retry import Retry | ||
|
|
||
| from .utils import chain_ids_by_name | ||
|
|
||
|
|
||
| class Etherscan: | ||
| BASE_URL = "https://api.etherscan.io/v2/api" | ||
|
|
||
| def __init__(self, api_key: Optional[str] = None): | ||
| self.api_key = api_key or os.getenv("ETHERSCAN_API_KEY") | ||
| if not self.api_key: | ||
| raise ValueError( | ||
| "Etherscan API key required. Set ETHERSCAN_API_KEY environment variable or pass api_key parameter" | ||
| ) | ||
|
|
||
| self.session = requests.Session() | ||
| retry_strategy = Retry( | ||
| total=3, | ||
| backoff_factor=0.5, | ||
| status_forcelist=[429, 500, 502, 503, 504], | ||
| ) | ||
| adapter = HTTPAdapter(max_retries=retry_strategy) | ||
| self.session.mount("http://", adapter) | ||
| self.session.mount("https://", adapter) | ||
|
|
||
| self.last_request_time = 0 | ||
| self.rate_limit_delay = 0.2 # 200ms | ||
|
|
||
| def _get_chain_id(self, chain: str) -> int: | ||
| chain_ids = chain_ids_by_name() | ||
| if chain not in chain_ids: | ||
| raise ValueError( | ||
| f"Unsupported chain: {chain}. Supported chains: {list(chain_ids.keys())}" | ||
| ) | ||
| return chain_ids[chain] | ||
|
|
||
| def _rate_limit(self): | ||
| current_time = time.time() | ||
| time_since_last_request = current_time - self.last_request_time | ||
| if time_since_last_request < self.rate_limit_delay: | ||
| time.sleep(self.rate_limit_delay - time_since_last_request) | ||
| self.last_request_time = time.time() | ||
|
|
||
| def _make_request(self, params: Dict[str, Any]) -> Dict[str, Any]: | ||
| self._rate_limit() | ||
|
|
||
| params["apikey"] = self.api_key | ||
|
|
||
| response = self.session.get(self.BASE_URL, params=params, timeout=30) | ||
| response.raise_for_status() | ||
|
|
||
| data = response.json() | ||
|
|
||
| if data.get("status") == "0" and data.get("message") != "No records found": | ||
| raise Exception( | ||
| f"Etherscan API error: {data.get('message', 'Unknown error')}" | ||
| ) | ||
|
|
||
| return data | ||
|
|
||
| def get_block_by_timestamp( | ||
| self, chain: str, timestamp: int, closest: str = "before" | ||
| ) -> Optional[int]: | ||
| chain_id = self._get_chain_id(chain) | ||
|
|
||
| params = { | ||
| "chainid": chain_id, | ||
| "module": "block", | ||
| "action": "getblocknobytime", | ||
| "timestamp": timestamp, | ||
| "closest": closest, | ||
| } | ||
|
|
||
| try: | ||
| data = self._make_request(params) | ||
|
|
||
| if data.get("status") == "1" and data.get("result"): | ||
| return int(data["result"]) | ||
|
|
||
| return None | ||
|
|
||
| except Exception as e: | ||
| raise Exception( | ||
| f"Error fetching block for timestamp {timestamp} on {chain}: {str(e)}" | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,6 +3,8 @@ | |
| import json | ||
| import warnings | ||
| import time | ||
| import os | ||
| from datetime import datetime, timedelta | ||
|
|
||
| from bal_tools.subgraph import Subgraph, GqlChain, Pool, PoolSnapshot | ||
| from bal_tools.errors import NoPricesFoundError | ||
|
|
@@ -170,3 +172,27 @@ def test_get_pool_protocol_version(subgraph): | |
| ) | ||
| == 2 | ||
| ) | ||
|
|
||
|
|
||
| def test_get_first_block_after_utc_timestamp_with_etherscan( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nice and clean test |
||
| chain, subgraph_all_chains, chains_prod | ||
| ): | ||
| if not os.getenv("ETHERSCAN_API_KEY"): | ||
| pytest.skip("ETHERSCAN_API_KEY not set") | ||
|
|
||
| if chain not in chains_prod or chain in ["fantom", "sonic"]: | ||
| pytest.skip(f"Skipping {chain}") | ||
|
|
||
| test_timestamp = int((datetime.now() - timedelta(days=1)).timestamp()) | ||
|
|
||
| try: | ||
| block = subgraph_all_chains.get_first_block_after_utc_timestamp( | ||
| test_timestamp, use_etherscan=True | ||
| ) | ||
| assert isinstance(block, int) | ||
| assert block > 0 | ||
| except Exception as e: | ||
| if "Unsupported chain" in str(e) or "Error fetching block" in str(e): | ||
| pytest.skip(f"Chain {chain} not supported by Etherscan V2") | ||
| else: | ||
| raise | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Free tier is 5 calls per second, so this makes sense to me