-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
129 lines (104 loc) · 4.99 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import asyncio
import functools
import json
import random
import sys
from typing import Any, Dict, List, Optional
from tqdm import tqdm
from web3 import AsyncWeb3
from core.chain import MAINNET
from logger import logger
def read_from_json(file_path) -> Dict[str, Any]:
try:
with open(file_path) as json_file:
return json.load(json_file)
except FileNotFoundError:
logger.error(f"File '{file_path}' not found.")
except Exception as e:
logger.error(
f"Encountered an unexpected error while reading a JSON file '{file_path}': {e}."
)
sys.exit(1)
async def sleep(
delay_range: List[int], send_message: bool = True, pr_bar: bool = True
) -> None:
delay = random.randint(*delay_range)
if send_message:
logger.info(f"Sleeping for {delay} seconds...")
if pr_bar:
with tqdm(
total=delay, desc="Waiting", unit="s", dynamic_ncols=True, colour="blue"
) as pbar:
for _ in range(delay):
await asyncio.sleep(delay=1)
pbar.update(1)
else:
await asyncio.sleep(delay=delay)
def retry(tries: int, retry_delay_range: Optional[List[int]] = [5, 10]):
def decorator(func):
@functools.wraps(func)
async def wrapper(*args, **kwargs):
for _ in range(tries):
result = await func(*args, **kwargs)
if result is None or result is False:
await sleep(delay_range=retry_delay_range, send_message=False)
else:
return result
return False
return wrapper
return decorator
def read_from_txt(file_path: str) -> List[str]:
try:
with open(file_path, "r") as file:
return [line.strip() for line in file]
except FileNotFoundError as e:
logger.error(f"File `{file_path}` not found.")
except PermissionError as e:
logger.error(f"Permission error while reading `{file_path}`: {e}")
except Exception as e:
logger.error(f"Error while reading `{file_path}`: {e}")
sys.exit(1)
def menu_message() -> None:
logger.debug(
r"""
__ ' _ ,., ,., ' ‘ _ ‘
,·:'´/::::/'`;·., '/:::::/`, /:::/'; /:¯:'`:*:^:*:´':¯::/'`;‘
.:´::::/::::/:::::::`; /;: :;/:::\ /;:;/:'i‘ /:: :: : : : : : :::/::'/
/:;:· '´ ¯¯'`^·-;::::/' ‘ ,´ `;::'; ,´ 'i:'i ,´¯ '` * ^ * ´' ¯ '`;/ ‘
/·´ _ '`;/‘ i \::', ,: 'i:'; '`, ,·' '
'i ;::::'`;* ; ';::\ .,_'; ';:'i' '`*^*'´; .´ ‘
`; '`;:::::'`:, '; ';::/::::'; ;':; .´ .' _ ' ‘
`·, '`·;:::::'; \ \/::::;' i:/'° .´ ,'´~:~/:::/`:,
,~:-'`·, `:;::/' '\ '`~'´ ,'/ .´ ,'´::::::/:::/:::'i‘
/:::::::::'; ';/ \ / ,' '*^~·~*'´¯'`·;:/
,:~·- . -·'´ ,'´ '`, ;' / ,'/
'`·, , ·'´ `·., ,.·´ '; ,.´
'`*^·–·^*'´' ‘ ¯ ° '`*^~–––––-·~^'´
___ _ _ ____ / ____ _ _ ___ _ _ _ _ ___ ____ _ _ ____ _ _ ____
| |\/| |___ / [__ \_/ |__] | | | | / |__| |_/ | | |\ | |___
| .| | |___ / ___] | |__] | |___ ___ \/ ___ /__ | | | \_ |__| | \| |___
1. [DATABASE] Создать базу данных | Create database
2. [MINTER] Origins NFT минтер | Origins NFT minter
"""
)
async def get_eth_gas_fee():
w3 = AsyncWeb3(AsyncWeb3.AsyncHTTPProvider(MAINNET.rpc))
return await w3.eth.gas_price
def gas_delay(gas_threshold: int, delay_range: list):
def decorator(func):
@functools.wraps(func)
async def wrapper(*args, **kwargs):
while True:
current_eth_gas_price = await get_eth_gas_fee()
threshold = AsyncWeb3.to_wei(gas_threshold, "gwei")
if current_eth_gas_price > threshold:
random_delay = random.randint(*delay_range)
logger.warning(
f"Current gas fee {round(AsyncWeb3.from_wei(current_eth_gas_price, 'gwei'), 2)} GWEI > Gas threshold {AsyncWeb3.from_wei(threshold, 'gwei')} GWEI. Waiting for {random_delay} seconds..."
)
await sleep(delay_range=delay_range, send_message=False)
else:
break
return await func(*args, **kwargs)
return wrapper
return decorator