-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.py
151 lines (115 loc) · 4.36 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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# Copyright 2021 [email protected]
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be included in all copies
# or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import sys
import datetime as dt
import time
from pydantic import BaseModel, Field, validator
from typing import Union, Optional
def ensure_pk(func):
def deco(self, *args, **kwargs):
if self.pk is None:
print("Aborting: Please provide a private_key to call this function.")
sys.exit()
return func(self, *args, **kwargs)
return deco
def no_retry(f, *args, **kwargs):
return f(*args, **kwargs)
def linear_retry(f, *args, post_call=lambda x: x, **kwargs):
for try_ in range(1, 10000):
try:
res = f(*args, **kwargs)
res = post_call(res)
return res
except:
time.sleep(try_)
def paginate(func, *args, retry_strategy=no_retry, **kwargs):
cursor = ""
while True:
res = retry_strategy(func, *args, **kwargs, cursor=cursor)
# DEBUG
# print(res)
cursor = res["cursor"]
if res is None:
break
res = res["result"]
if not res:
return
yield res
if not cursor:
break
def all_pages(func, *args, key=None, retry_strategy=no_retry, **kwargs):
results = []
for res in paginate(func, *args, retry_strategy=retry_strategy, **kwargs):
results.extend(res)
if key is not None:
results = make_unique(results, key=key)
return results
def make_unique(iterable, key=None):
keys = set()
idxs_to_remove = []
for idx, val in enumerate(iterable):
k = key(val)
if k not in keys:
keys.add(k)
else:
idxs_to_remove.append(idx)
for counter, idx in enumerate(idxs_to_remove):
iterable.pop(idx - counter)
return iterable
class IMXTime:
format_ = "%Y-%m-%dT%H:%M:%S.%fZ"
@staticmethod
def from_str(timestamp_str):
return dt.datetime.strptime(timestamp_str, IMXTime.format_)
@staticmethod
def to_str(timestamp):
return timestamp.strftime(IMXTime.format_)
@staticmethod
def now():
return dt.datetime.utcnow()
class SafeNumber:
def __init__(self, number, decimals=None, as_wei=False):
self.value = self.convert_to_safe(number, decimals, as_wei)
def convert_to_safe(self, number, decimals, as_wei):
if not isinstance(number, (int, str)):
raise ValueError("SafeNumber: Only 'str' and 'int' numbers allowed.")
if as_wei:
# raises if there are fobidden chars in str
return str(int(number))
number = str(number)
if "." not in number:
before_comma, after_comma = number, ""
else:
before_comma, after_comma = number.split(".")
if len(after_comma) > decimals:
raise ValueError(
f"More decimals present than allowed\n\tnumber: {number}\n\t:decimals: {decimals}"
)
len_padding = decimals - len(after_comma)
padding = "".join("0" for _ in range(len_padding))
safe_number = ""
if int(before_comma):
safe_number = before_comma + after_comma + padding
# happens when a 0 is put in
elif not after_comma:
safe_number = "0"
else:
# remove leading zeros and append
safe_number = str(int(after_comma)) + padding
return safe_number