-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.py
279 lines (237 loc) · 9.45 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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import random
from typing import List
from decimal import Decimal
from datetime import datetime, timedelta, timezone
import aiohttp
import sentry_sdk
from tortoise.functions import Count
from tortoise.query_utils import Q
from discord.ext import commands
from discord_slash.utils.manage_commands import create_option, create_choice
import config
from app.models import User, Lottery
from app.constants import LotteryStatus
from app.exceptions import BlockAlreadyMinedException
def use_sentry(client, **sentry_args):
"""
Use this compatibility library as a bridge between Discord and Sentry.
Arguments:
client: The Discord client object (e.g. `discord.AutoShardedClient`).
sentry_args: Keyword arguments to pass to the Sentry SDK.
"""
sentry_sdk.init(**sentry_args)
@client.event
async def on_error(event, *args, **kwargs):
"""Don't ignore the error, causing Sentry to capture it."""
raise
@client.event
async def on_command_error(msg, error):
# don't report errors to sentry related to wrong permissions
if not isinstance(
error,
(
commands.MissingRole,
commands.MissingAnyRole,
commands.BadArgument,
commands.MissingRequiredArgument,
commands.errors.CommandNotFound,
),
):
raise error
def pp_points(balance: Decimal) -> str:
"""Pretty print points"""
str_balance = f"{balance:.1f}"
suffix = ".0"
# backport from Python 3.9 https://docs.python.org/3/library/stdtypes.html#str.removesuffix
if suffix and str_balance.endswith(suffix):
return str_balance[: -len(suffix)]
else:
return str_balance[:]
async def ensure_registered(user_id: int) -> User:
"""Ensure that user is registered in our database"""
user, _ = await User.get_or_create(id=user_id)
return user
async def get_eta_to_block(block: int) -> datetime:
"""Get ETA to block
Raises: BlockAlreadyMinedException if block already passed
"""
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://api.etherscan.io/api?module=block&action=getblockcountdown&blockno={block}&apikey={config.ETHERSCAN_API_KEY}" # noqa: E501
) as response:
try:
response_json = await response.json()
eta_in_seconds = int(float(response_json["result"]["EstimateTimeInSec"]))
strike_date_eta = datetime.now(tz=timezone.utc) + timedelta(seconds=eta_in_seconds)
return strike_date_eta
except TypeError:
raise BlockAlreadyMinedException()
async def get_hash_for_block(block: int) -> str:
"""Function which will get block hash for block
Returns:
block hash
"""
async with aiohttp.ClientSession() as session:
block_hex = hex(block)
async with session.get(
f"https://api.etherscan.io/api?module=proxy&action=eth_getBlockByNumber&tag={block_hex}&boolean=true&apikey={config.ETHERSCAN_API_KEY}" # noqa: E501
) as response:
block_info = await response.json()
return block_info["result"]["hash"]
async def get_old_winning_pool() -> int:
"""Return winning pool for past lotteries without winners (aka with 'ended' status and has_winners="False")"""
qs = (
await Lottery.filter(Q(status=LotteryStatus.ENDED) & Q(has_winners=False))
.prefetch_related("tickets")
.annotate(total_tickets=Count("tickets"))
)
# TODO: waiting for response to rewrite this into orm
# https://github.com/tortoise/tortoise-orm/issues/683
return sum([_.total_tickets * _.ticket_price for _ in qs])
async def register_view_lottery_command(bot, cmd) -> None:
"""Dirty hack to register options on fly for view_lottery command"""
lotteries = await Lottery.all().order_by("-created_at").limit(10)
try:
# force sync_commands to detect new changes and sync slash commands with Discord
del bot.slash.subcommands["sweepstake"]["view"]
except KeyError:
pass
bot.slash.add_subcommand(
cmd=cmd,
base="sweepstake",
name="view",
description="Display sweepstake information",
guild_ids=config.GUILD_IDS,
options=[
create_option(
name="name",
description="choose sweepstake",
option_type=3,
required=True,
choices=[create_choice(name=_.name, value=_.name) for _ in lotteries],
)
],
)
return None
async def register_buy_ticket_command(bot, cmd) -> None:
"""Dirty hack to register options on fly for buy_ticket command"""
lotteries = await Lottery.filter(status=LotteryStatus.STARTED).order_by("-created_at").limit(10)
try:
# force sync_commands to detect new changes and sync slash commands with Discord
del bot.slash.subcommands["sweepstake"]["buy"]
except KeyError:
pass
bot.slash.add_subcommand(
cmd=cmd,
base="sweepstake",
name="buy",
description="Buy ticket",
guild_ids=config.GUILD_IDS,
options=[
create_option(
name="name",
description="choose sweepstake",
option_type=3,
required=True,
choices=[create_choice(name=_.name, value=_.name) for _ in lotteries],
)
],
)
return None
async def register_buy_whitelisted_command(bot, cmd) -> None:
"""Dirty hack to register options on fly for buy_whitelisted command"""
lotteries = await Lottery.filter(status=LotteryStatus.STARTED).order_by("-created_at").limit(10)
try:
# force sync_commands to detect new changes and sync slash commands with Discord
del bot.slash.subcommands["sweepstake_admin"]["buy_whitelisted"]
except KeyError:
pass
bot.slash.add_subcommand(
cmd=cmd,
base="sweepstake_admin",
name="buy_whitelisted",
description="Batch Buy Whitelisted tickets (admins only)",
guild_ids=config.GUILD_IDS,
options=[
create_option(
name="name",
description="choose sweepstake",
option_type=3,
required=True,
choices=[create_choice(name=_.name, value=_.name) for _ in lotteries],
)
],
)
return None
async def register_my_tickets_command(bot, cmd) -> None:
"""Dirty hack to register options on fly for my_tickets command"""
lotteries = await Lottery.all().order_by("-created_at").limit(10)
try:
# force sync_commands to detect new changes and sync slash commands with Discord
del bot.slash.subcommands["sweepstake"]["tickets"]
except KeyError:
pass
bot.slash.add_subcommand(
cmd=cmd,
base="sweepstake",
name="tickets",
description="My tickets",
guild_ids=config.GUILD_IDS,
options=[
create_option(
name="name",
description="choose sweepstake",
option_type=3,
required=True,
choices=[create_choice(name=_.name, value=_.name) for _ in lotteries],
)
],
)
return None
async def reload_options_hack(bot) -> None:
"""dirty hack to fake dynamic loading of choices in slash commands"""
await register_view_lottery_command(bot, bot.cogs["LotteryCog"].view_lottery)
await register_buy_ticket_command(bot, bot.cogs["TicketCog"].buy_ticket)
await register_buy_whitelisted_command(bot, bot.cogs["TicketCog"].buy_whitelisted)
await register_my_tickets_command(bot, bot.cogs["TicketCog"].my_tickets)
bot.reload_extension("app.extensions.lottery")
def select_winning_tickets(
hash: str,
min_number: int,
max_number: int,
number_of_winning_tickets: int = 1,
) -> List[int]:
"""Function will act as VRF (https://en.wikipedia.org/wiki/Verifiable_random_function)
Args:
hash (str): block hash, will be used as seed for verifiable randomness
min_number (int): start of the range
max_number (int): end of the range for generating winning numbers for tickets
number_of_winning_tickets (int): number of winning tickets
Example:
select_winning_tickets("hash", 1, 10) will generate numbers between 1 and 10
Returns:
list of winning ticket numbers
"""
vrf_random = random.Random(hash)
# make range to behave as inclusive range, this way ticket with max_number could be won
return vrf_random.sample(range(min_number, max_number + 1), number_of_winning_tickets)
def select_winning_tickets_guaranteed(
hash: str,
ticket_numbers: list,
number_of_winning_tickets: int = 1,
) -> List[int]:
"""Function will act as VRF (https://en.wikipedia.org/wiki/Verifiable_random_function)
Args:
hash (str): block hash, will be used as seed for verifiable randomness
ticket_numbers (list): list of ticket numbers
number_of_winning_tickets (int): number of winning tickets
Example:
select_winning_tickets_guaranteed("hash", [1, 2, 99], 10) will select winning ticket from three tickets
Returns:
list of winning ticket numbers
"""
vrf_random = random.Random(hash)
if len(ticket_numbers) >= number_of_winning_tickets:
return vrf_random.sample(ticket_numbers, number_of_winning_tickets)
else:
return ticket_numbers