chain_harvester 0.1.0__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023, 0xCommanderKeen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.1
2
+ Name: chain-harvester
3
+ Version: 0.1.0
4
+ Summary: A Python library designed to interface with various blockchain networks, enabling the retrieval of data.
5
+ Home-page: https://github.com/blockanalitica/chain-harvester
6
+ Author: 0xCommanderKeen
7
+ Author-email: f91289621+0xCommanderKeen@users.noreply.github.com
8
+ Requires-Python: >=3.8,<4.0
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.8
11
+ Classifier: Programming Language :: Python :: 3.9
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Requires-Dist: requests (>=2.31.0,<3.0.0)
15
+ Requires-Dist: web3 (>=6.8.0,<7.0.0)
16
+ Project-URL: Documentation, https://blockanalitica.github.io/chain-harvester/
17
+ Project-URL: Repository, https://github.com/blockanalitica/chain-harvester
18
+ Description-Content-Type: text/markdown
19
+
20
+ # chain-harvester
21
+
22
+ A Python library designed to interface with various blockchain networks, enabling the retrieval of data.
23
+
24
+ - **Github repository**: <https://github.com/blockanalitica/chain-harvester/>
25
+ - **Documentation** <https://blockanalitica .github.io/chain-harvester/>
26
+
27
+
@@ -0,0 +1,7 @@
1
+ # chain-harvester
2
+
3
+ A Python library designed to interface with various blockchain networks, enabling the retrieval of data.
4
+
5
+ - **Github repository**: <https://github.com/blockanalitica/chain-harvester/>
6
+ - **Documentation** <https://blockanalitica .github.io/chain-harvester/>
7
+
File without changes
@@ -0,0 +1,247 @@
1
+ import inspect
2
+ import json
3
+ import logging
4
+ import os
5
+
6
+ import requests
7
+ from requests.adapters import HTTPAdapter
8
+ from requests.packages.urllib3.util.retry import Retry
9
+ from web3 import Web3
10
+ from web3.middleware import geth_poa_middleware
11
+
12
+ log = logging.getLogger(__name__)
13
+
14
+
15
+ class Chain:
16
+ def __init__(
17
+ self,
18
+ rpc=None,
19
+ chain=None,
20
+ step=None,
21
+ etherscan_api_key=None,
22
+ abis_path=None,
23
+ chain_id=None,
24
+ *args,
25
+ **kwargs,
26
+ ):
27
+ super().__init__(*args, **kwargs)
28
+ self.rpc = rpc
29
+ self._chain = chain
30
+ self.step = step or 10_000
31
+ self.provider = rpc
32
+ self.etherscan_api_key = etherscan_api_key
33
+ self.abis_path = abis_path
34
+ self.chain_id = chain_id
35
+
36
+ self._abis = {}
37
+ self.current_block = 0
38
+ self.retry = 0
39
+
40
+ @property
41
+ def chain(self):
42
+ if not self._chain:
43
+ session = requests.Session()
44
+ retries = 3
45
+ retry = Retry(
46
+ total=retries,
47
+ read=retries,
48
+ connect=retries,
49
+ backoff_factor=0.5,
50
+ status_forcelist=(429,),
51
+ respect_retry_after_header=True,
52
+ )
53
+ adapter = HTTPAdapter(max_retries=retry)
54
+ session.mount("http://", adapter)
55
+ session.mount("https://", adapter)
56
+
57
+ self._chain = Web3(Web3.HTTPProvider(self.rpc, request_kwargs={"timeout": 60}, session=session))
58
+ self._chain.middleware_onion.inject(geth_poa_middleware, layer=0)
59
+ return self._chain
60
+
61
+ @property
62
+ def eth(self):
63
+ return self.chain.eth
64
+
65
+ def get_block_info(self, block_number):
66
+ return self.eth.get_block(block_number)
67
+
68
+ def get_latest_block(self):
69
+ return self.eth.get_block_number()
70
+
71
+ def get_abi_from_etherscan(self, contract_address):
72
+ try:
73
+ req = requests.get(
74
+ "https://api.etherscan.io/api?module=contract&action=getabi&address="
75
+ + contract_address
76
+ + "&apikey="
77
+ + self.etherscan_api_key,
78
+ timeout=5,
79
+ )
80
+ except requests.exceptions.Timeout:
81
+ log.exception("Timeout when get abi from etherscan", extra={"contract_address": contract_address})
82
+ raise
83
+ resp = json.loads(req.text)
84
+ abi = json.loads(resp["result"])
85
+ return abi
86
+
87
+ def load_abi(self, contract_address):
88
+ contract_address = contract_address.lower()
89
+ if contract_address not in self._abis:
90
+ if not os.path.exists(self.abis_path):
91
+ os.makedirs(self.abis_path)
92
+ current_file_path = inspect.getfile(inspect.currentframe())
93
+ current_directory = os.path.dirname(os.path.abspath(current_file_path))
94
+ file_path = os.path.join(current_directory, "abis", f"{contract_address}.json")
95
+ if os.path.exists(file_path):
96
+ with open(file_path) as f:
97
+ self._abis[contract_address] = json.loads(f.read())
98
+ else:
99
+ abi = self.get_abi_from_etherscan(contract_address)
100
+
101
+ with open(file_path, "w") as f:
102
+ json.dump(abi, f)
103
+ with open(file_path) as f:
104
+ self._abis[contract_address] = json.loads(f.read())
105
+ return self._abis[contract_address]
106
+
107
+ def get_contract(self, contract_address):
108
+ if Web3.is_address(contract_address):
109
+ contract_address = Web3.to_checksum_address(contract_address)
110
+ abi = self.load_abi(contract_address)
111
+ return self.chain.eth.contract(address=contract_address, abi=abi)
112
+
113
+ def call_contract_function(self, contract_address, function_name, *args, **kwargs):
114
+ contract_address = Web3.to_checksum_address(contract_address)
115
+ contract = self.get_contract(contract_address)
116
+ contract_function = contract.get_function_by_name(function_name)
117
+ result = contract_function(*args).call(block_identifier=kwargs.get("block_identifier", "latest"))
118
+ return result
119
+
120
+ def get_storage_at(self, contract_address, position, block_identifier=None):
121
+ contract_address = Web3.to_checksum_address(contract_address)
122
+ content = self.eth.get_storage_at(contract_address, position, block_identifier=block_identifier).hex()
123
+ return content
124
+
125
+ def _yield_events(self, fetch_events_func, from_block, to_block=None):
126
+ self.current_block = 0
127
+ if not to_block:
128
+ to_block = self.get_latest_block()
129
+
130
+ start_block = from_block
131
+ while True:
132
+ end_block = min(start_block + self.step - 1, to_block)
133
+ events = fetch_events_func(start_block, end_block, self.step)
134
+ if events is None:
135
+ break
136
+ else:
137
+ yield events
138
+ if self.current_block >= to_block:
139
+ break
140
+ start_block = self.current_block
141
+
142
+ def _return_events_with_retry(self, fetch_events_func, start_block, end_block, step, extra_log):
143
+ MAX_RETRIES = 3
144
+ retry = 0
145
+ while retry <= MAX_RETRIES:
146
+ try:
147
+ events = fetch_events_func(start_block, end_block, step)
148
+ except ValueError as e:
149
+ msg = e.args[0]
150
+ if isinstance(msg, dict) and msg["code"] in [-32602, -32005, -32000]:
151
+ step /= 5
152
+ end_block = int(start_block + step - 1)
153
+ continue
154
+ else:
155
+ log_extra = {
156
+ "stack": True,
157
+ "start_block": start_block,
158
+ "end_block": end_block,
159
+ "step": step,
160
+ "exception": e,
161
+ "retry": retry,
162
+ **extra_log,
163
+ }
164
+ if retry == MAX_RETRIES:
165
+ log.exception(msg, extra=log_extra)
166
+ return None
167
+ else:
168
+ log.warning(msg, extra=log_extra)
169
+ retry += 1
170
+ else:
171
+ self.current_block = end_block
172
+ return events
173
+ return None
174
+
175
+ ### Topics
176
+
177
+ def _return_events_by_topics(self, contract_address, topics, start_block, end_block, step):
178
+ filters = {
179
+ "fromBlock": start_block,
180
+ "toBlock": end_block,
181
+ "address": contract_address,
182
+ "topics": topics,
183
+ }
184
+ events = self.eth.get_logs(filters)
185
+ return events
186
+
187
+ def _return_events_by_topic_with_retry(self, contract_address, topics, start_block, end_block, step, extra_log):
188
+ def fetch_events_func(start_block, end_block, step):
189
+ return self._return_events_by_topics(contract_address, topics, start_block, end_block, step)
190
+
191
+ return self._return_events_with_retry(fetch_events_func, start_block, end_block, step, extra_log)
192
+
193
+ def yield_contract_events_by_topic(self, contract_address, topics, from_block, to_block=None):
194
+ contract_address = Web3.to_checksum_address(contract_address)
195
+
196
+ def fetch_events_func(start_block, end_block, step):
197
+ return self._return_events_by_topic_with_retry(
198
+ contract_address,
199
+ topics,
200
+ start_block,
201
+ end_block,
202
+ step,
203
+ extra_log={"topics": topics, "contract_address": contract_address},
204
+ )
205
+
206
+ return self._yield_events(fetch_events_func, from_block, to_block)
207
+
208
+ ### Event Attr
209
+
210
+ def _return_contract_events(self, contract, event_attr, start_block, end_block, step):
211
+ attr = contract.events
212
+ cls = getattr(attr, event_attr)
213
+ caller = cls.create_filter
214
+ events = caller(fromBlock=start_block, toBlock=end_block)
215
+ entries = events.get_all_entries()
216
+ return entries
217
+
218
+ def _return_contract_events_with_retry(self, contract, event_attr, start_block, end_block, step, extra_log):
219
+ def fetch_events_func(start_block, end_block, step):
220
+ return self._return_contract_events(contract, event_attr, start_block, end_block, step)
221
+
222
+ return self._return_events_with_retry(
223
+ fetch_events_func,
224
+ start_block,
225
+ end_block,
226
+ step,
227
+ extra_log={"contract": contract, "event_attr": event_attr, **extra_log},
228
+ )
229
+
230
+ def yield_contract_events(self, contract_address, event_attr, from_block, to_block=None, **kwargs):
231
+ abi_address = kwargs.get("abi_type", contract_address)
232
+ contract = self.get_contract(abi_address)
233
+
234
+ def fetch_events_func(start_block, end_block, step):
235
+ return self._return_contract_events_with_retry(
236
+ contract,
237
+ event_attr,
238
+ start_block,
239
+ end_block,
240
+ step,
241
+ extra_log={
242
+ "event_attr": event_attr,
243
+ "contract_address": contract.address,
244
+ },
245
+ )
246
+
247
+ return self._yield_events(fetch_events_func, from_block, to_block)
@@ -0,0 +1,86 @@
1
+ [tool.poetry]
2
+ name = "chain_harvester"
3
+ version = "v0.1.0"
4
+ description = "A Python library designed to interface with various blockchain networks, enabling the retrieval of data."
5
+ authors = ["0xCommanderKeen <f91289621+0xCommanderKeen@users.noreply.github.com>"]
6
+ repository = "https://github.com/blockanalitica/chain-harvester"
7
+ documentation = "https://blockanalitica.github.io/chain-harvester/"
8
+ readme = "README.md"
9
+ packages = [
10
+ {include = "chain_harvester"}
11
+ ]
12
+
13
+ [tool.poetry.dependencies]
14
+ python = ">=3.8,<4.0"
15
+ web3 = "^6.8.0"
16
+ requests = "^2.31.0"
17
+
18
+ [tool.poetry.group.dev.dependencies]
19
+ pytest = "^7.4.0"
20
+ pre-commit = "^3.3.3"
21
+ tox = "^4.6.4"
22
+
23
+
24
+ [tool.poetry.group.docs.dependencies]
25
+ mkdocs = "^1.5.2"
26
+ mkdocs-material = "^9.1.0"
27
+ mkdocstrings-python = "1.2.1"
28
+ mkdocstrings = "0.22"
29
+
30
+ [build-system]
31
+ requires = ["poetry-core>=1.0.0"]
32
+ build-backend = "poetry.core.masonry.api"
33
+
34
+ [tool.black]
35
+ line-length = 120
36
+ target-version = ['py37']
37
+ preview = true
38
+
39
+ [tool.ruff]
40
+ target-version = "py37"
41
+ line-length = 120
42
+ fix = true
43
+ select = [
44
+ # flake8-2020
45
+ "YTT",
46
+ # flake8-bandit
47
+ "S",
48
+ # flake8-bugbear
49
+ "B",
50
+ # flake8-builtins
51
+ "A",
52
+ # flake8-comprehensions
53
+ "C4",
54
+ # flake8-debugger
55
+ "T10",
56
+ # flake8-simplify
57
+ "SIM",
58
+ # isort
59
+ "I",
60
+ # mccabe
61
+ "C90",
62
+ # pycodestyle
63
+ "E", "W",
64
+ # pyflakes
65
+ "F",
66
+ # pygrep-hooks
67
+ "PGH",
68
+ # pyupgrade
69
+ "UP",
70
+ # ruff
71
+ "RUF",
72
+ # tryceratops
73
+ "TRY",
74
+ ]
75
+ ignore = [
76
+ # LineTooLong
77
+ "E501",
78
+ # DoNotAssignLambda
79
+ "E731",
80
+ ]
81
+
82
+ [tool.ruff.per-file-ignores]
83
+ "tests/*" = ["S101"]
84
+
85
+
86
+