forked from praskoson/distribution-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflat-distributor.py
631 lines (556 loc) · 22.3 KB
/
flat-distributor.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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
#!/usr/bin/env python3
from datetime import datetime, timezone
import time
import argparse
import sys
import signal
import os
import subprocess
import re
def get_env():
envre = re.compile(r'''^([^\s=]+)=(?:[\s"']*)(.+?)(?:[\s"']*)$''')
result = {}
try:
with open('./config.env') as ins:
for line in ins:
match = envre.match(line)
if match is not None:
result[match.group(1)] = match.group(2)
except (OSError, IOError):
return False, None
# sys.exit(f"Error opening environment config file.\n{e.strerror}")
return True, result
def input_number(prompt):
while True:
try:
num = float(input(prompt))
break
except ValueError:
pass
return num
def display_menu(options):
for i in range(len(options)):
print("{:d}. {:s}".format(i+1, options[i]))
choice = 0
possible = list(range(1, len(options)+1))
while choice not in possible:
choice = input_number("Select an option:\n> ")
return choice
def get_current_utc_time_str():
now_utc = datetime.now(timezone.utc)
return now_utc.strftime("%Y-%m-%d-%H%M%S")
def amount_prompt(amount):
if amount is None:
value = 0
while True:
try:
str = input(
"No airdrop amount was specified. Please enter the amount. \n> ")
value = float(str.strip())
if value > 0:
break
else:
print("Airdrop amount must be greater than 0.")
except ValueError:
print("Not a float.")
return value
else:
return amount
def continue_airdrop_prompt(interactive, separator):
mode = 'interactive' if interactive else 'non-interactive'
interactive_msg = f'{bcolors.BOLD}You will be prompted to confirm each transaction.{bcolors.ENDC}'
uninteractive_msg = f'{bcolors.BOLD}The airdrop will run without additional confirmations.{bcolors.ENDC}'
detailed_info = interactive_msg if interactive else uninteractive_msg
print(
f"Running the airdrop in {bcolors.BOLD}{mode} mode{bcolors.ENDC}. {bcolors.BOLD}{detailed_info}{bcolors.ENDC}")
print(f"{bcolors.WARNING}{separator}{bcolors.ENDC}")
if input(f"Enter {bcolors.OKGREEN}Y{bcolors.ENDC} to proceed\n> ") != 'Y':
sys.exit("Cancelling the airdrop.")
def single_transaction_prompt(full_cmd, amount, recipient, decimals):
msg = f"Sending {bcolors.OKBLUE}{amount:,.{decimals}f}{bcolors.ENDC} tokens to recipient at: {bcolors.OKCYAN}{recipient}{bcolors.ENDC}.\n"
msg += "Cmd to be ran: \n"
msg += f" {bcolors.BOLD}" + full_cmd + f"{bcolors.ENDC}"
print(msg, flush=True)
choice = input(
"Press ENTER to confirm | Type anything to CANCEL | Type ALL to switch to non-interactive mode\n> ")
if choice == "":
return True, False
elif choice == "ALL":
return False, True
else:
return False, False
def gen_logfile(name, current_time, folder_prefix):
filename = "./" + folder_prefix + current_time + "/" + name
os.makedirs(os.path.dirname(filename), exist_ok=True)
# Don't open, but create it anyway
f = open(filename, "w")
f.close()
return filename
def parse_sig(log):
# Find the last line that has some text in it.
# That line should have the signature.
outlines = re.split('\n', log)
idx = len(outlines) - 1
while outlines[idx] == '':
idx = idx - 1
out = outlines[idx]
sig = re.match(r"Signature: ([a-zA-Z0-9]+)", out)
if sig:
return sig.group(1)
else:
return 'Error parsing signature - check the detailed logs.'
def run(cmd):
proc = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout, stderr = proc.communicate()
return proc.returncode, stdout, stderr
def try_transfer(cmd, addr, drop, log_success, log_unconfirmed, log_failed,
TOO_MANY_REQUESTS, RPC_ERROR, UNCONFIRMED):
log_detail_entry = ''
while True:
code, out, err = run(cmd.to_list())
if code == 0:
output = out.decode('utf-8')
print(
f'{bcolors.OKGREEN}SUCCESS{bcolors.ENDC}', flush=True)
sig = parse_sig(output)
with open(log_success, 'a') as ls:
ls.write(f'{addr},{drop:f},{sig}\n')
log_detail_entry += output + '\n'
break
else:
err_msg = err.decode('utf-8')
if RPC_ERROR in err_msg:
print('-32005 RPC Error, waiting 5... ',
end='', flush=True)
log_detail_entry += err_msg + '\n'
time.sleep(5)
continue
if RETRY_ON_429 and (TOO_MANY_REQUESTS in err_msg):
print('429, waiting 5... ', end='', flush=True)
time.sleep(5)
log_detail_entry += err_msg + '\n'
continue
if UNCONFIRMED in err_msg or TOO_MANY_REQUESTS in err_msg:
print(
f'{bcolors.DANGER}UNCONFIRMED{bcolors.ENDC}', flush=True)
with open(log_unconfirmed, "a") as lu:
lu.write(f'{addr},{drop:f},{err_msg}')
log_detail_entry += err_msg + '\n'
break
print(f'{bcolors.FAIL}FAILED{bcolors.ENDC}', flush=True)
try:
err_short = err_msg.split('\n', 1)[0] + '\n'
err_short = re.sub(r"[,]", ' ', err_short)
except (IndexError, Exception):
err_short = 'Error parsing error description - read the full logs.\n'
finally:
with open(log_failed, 'a') as lfa:
lfa.write(f'{addr},{drop:f},{err_short}')
log_detail_entry += err_msg + '\n'
break
return log_detail_entry
def get_assoc_addr(addr, mint, url):
cmd = ['spl-token', 'address', '--token', mint, '--owner', addr,
'--url', url, '--verbose']
code, output, _ = run(cmd)
if code == 0:
decoded = output.decode('utf-8')
out = (re.split('\n', decoded))[1]
assoc = re.match(r"Associated token address: ([a-zA-Z0-9]+)", out)
return True, assoc.group(1)
else:
return False, None
def get_balance(addr, addr_type, mint, url):
if addr_type == 'token':
cmd = ['spl-token', 'balance', '--address', addr, '--url', url]
code, output, _ = run(cmd)
if code == 0 and output.decode('utf-8') != '':
return True, float(output.decode('utf-8'))
else:
return False, 'Could not find token account'
else:
ok, assoc_addr = get_assoc_addr(addr, mint, url)
if ok:
cmd = ['spl-token', 'balance',
'--address', assoc_addr, '--url', url]
code, output, _ = run(cmd)
if code == 0 and output.decode('utf-8') != 0:
return True, float(output.decode('utf-8'))
else:
return False, 'Could not find token account'
else:
return False, 'Could not find token account'
class TransferCmd:
def __init__(self, cmd, instruction, mint_address, decimals, drop_amount, recipient, url, options=None):
self.cmd = cmd
self.instruction = instruction
self.mint_address = mint_address
self.decimals = decimals
self.drop_amount = drop_amount
self.recipient = recipient
self.url = url
if options is None:
self.options = []
else:
self.options = options
def to_str(self):
return f"{self.cmd} {self.instruction} {self.mint_address} {self.drop_amount:.{self.decimals}f} {self.recipient} {' '.join(self.options)}"
def to_list(self):
#obj = [self.cmd, self.instruction, self.mint_address, str(self.drop_amount), self.recipient]
obj = [self.cmd, self.instruction, self.mint_address,
f"{self.drop_amount:.{self.decimals}f}", self.recipient, '--url', self.url]
if self.options:
obj.extend(self.options)
return obj
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
DANGER = '\u001b[38;5;208m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def main():
global TOKEN_MINT, TOKEN_DECIMALS, RPC_URL, LOG_FOLDER_PREFIX, FULL_LOGS, SUCCESS_LOGS, FAILED_LOGS, CANCELED_LOGS, UNCONFIRMED_LOGS, RETRY_ON_429
args = parser.parse_args()
mode = args.mode
if not mode:
sys.exit('Select a subcommand (-h)')
ok, env = get_env()
if ok:
try:
TOKEN_MINT = env['TOKEN_MINT']
TOKEN_DECIMALS = env['TOKEN_DECIMALS']
RPC_URL = env['RPC_URL']
LOG_FOLDER_PREFIX = env["LOG_FOLDER_PREFIX"]
FULL_LOGS = env["FULL_LOGS"]
SUCCESS_LOGS = env["SUCCESS_LOGS"]
FAILED_LOGS = env["FAILED_LOGS"]
CANCELED_LOGS = env["CANCELED_LOGS"]
UNCONFIRMED_LOGS = env["UNCONFIRMED_LOGS"]
except KeyError as e:
sys.exit('Error reading config file: ' + str(e))
else:
if RPC_URL == "":
rpc_endpoints = {
'mainnet': 'https://api.mainnet-beta.solana.com',
'testnet': 'https://api.testnet.solana.com',
'devnet': 'https://api.devnet.solana.com'
}
print("Select an endpoint ")
choice = display_menu(list(rpc_endpoints.values()))
RPC_URL = rpc_endpoints[list(rpc_endpoints.keys())[int(choice)-1]]
if TOKEN_MINT == "":
TOKEN_MINT = input("\nEnter the token mint address:\n> ")
if TOKEN_DECIMALS == "":
TOKEN_DECIMALS = int(
input("\nEnter the number of token decimals:\n> "))
if mode == 'check-before':
input_file = args.file_name
address_type = args.address_type
drop = args.drop
before(input_file, drop, address_type)
elif mode == 'check-after':
before_file = args.before_file_name
addr_type = args.address_type
after(before_file, addr_type)
elif mode == 'transfer':
input_path = args.address_list
interactive = args.interactive
drop_amount = args.drop_amount
fund_recipient = args.fund_recipient
allow_unfunded_recipient = args.allow_unfunded_recipient
RETRY_ON_429 = args.retry_on_429
transfer(input_path, interactive,drop_amount,
fund_recipient, allow_unfunded_recipient
)
def before(input_file, drop, addr_type):
global TOKEN_MINT, TOKEN_DECIMALS, RPC_URL
output_file = './before.csv'
print('recipient,current-balance,expected-balance')
lines = []
with open(input_file, 'r') as f:
lines = f.readlines()
with open(output_file, 'w') as fw:
for line in lines:
try:
addr = line.strip()
ok, balance = get_balance(addr, addr_type, TOKEN_MINT, RPC_URL)
except (IndexError, ValueError) as e:
sys.exit('Error when reading input file: ' + str(e))
if ok:
expected = float(balance) + drop
print(f'{addr} - {balance:.3f} - {expected:.3f}')
fw.write(f'{addr},{balance:.{TOKEN_DECIMALS}f},{expected:.{TOKEN_DECIMALS}f}\n')
else:
print(f'{addr} - No token account - No token account')
fw.write(f'{addr},No token account,No token account\n')
def after(input_file, addr_type):
global TOKEN_MINT, TOKEN_DECIMALS, RPC_URL
lines = []
output_file = './after.csv'
print('recipient,expected-balance,actual-balance,difference')
with open(input_file, 'r') as f:
lines = f.readlines()
with open(output_file, 'w') as f:
# Read before.csv
for line in lines:
output_line = ''
try:
addr, _, expected = [x.strip() for x in line.split(',')]
output_line += f'{addr},'
except IndexError as e:
sys.exit('Error reading input file: ' + str(e))
try:
expected = float(expected)
output_line += f'{expected:.{TOKEN_DECIMALS}f},'
except ValueError:
# Not a number, expecting a No token account message
output_line += f'{expected},'
ok, actual = get_balance(addr, addr_type, TOKEN_MINT, RPC_URL)
if ok:
endc = '\033[0m'
startc = ''
try:
diff = actual - expected
if diff >= 0:
startc = '\033[92m'
else:
startc = '\033[91m'
output_line += f'{actual:.{TOKEN_DECIMALS}f},{diff:.{TOKEN_DECIMALS}f}'
except TypeError:
# Assuming actual was not a number
diff = 'NaN'
output_line += f'{actual},{diff}'
else:
output_line += f'{actual},NaN'
print(startc + output_line + endc)
f.write(output_line + '\n')
def transfer(input_path, interactive, drop_amount,
fund_recipient, allow_unfunded_recipient):
global TOKEN_MINT, TOKEN_DECIMALS, RPC_URL, LOG_FOLDER_PREFIX, FULL_LOGS, SUCCESS_LOGS, FAILED_LOGS, CANCELED_LOGS, UNCONFIRMED_LOGS
SEPARATOR = "-" * 50
LOG_SEPARATOR = "-" * 30 + "\n"
TOO_MANY_REQUESTS = "429 Too Many Requests"
UNCONFIRMED = "unable to confirm transaction"
RPC_ERROR = "RPC response error -32005"
signal.signal(signal.SIGINT, signal.default_int_handler)
supply_code, current_supply, _ = run(['solana', 'address'])
if supply_code != 0:
sys.exit('Exiting, failed to read the current supply account address. Try checking the output of \'solana address\'.')
print(f"{bcolors.DANGER}WARNING: MAKE SURE YOU ARE USING THE CORRECT WALLET/SUPPLY/ TO DISTRIBUTE.\nYOUR CURRENT WALLET ADDRESS IS: {current_supply.decode('utf-8')}{bcolors.ENDC}")
print(
f"Running airdrop for the Token Mint: {bcolors.OKGREEN}{TOKEN_MINT}{bcolors.ENDC}")
drop = amount_prompt(drop_amount)
print(
f"Airdrop amount: {bcolors.OKGREEN}{drop:,.{TOKEN_DECIMALS}f}{bcolors.ENDC}")
try:
with open(input_path) as f:
address_list = f.read().splitlines()
print(f'Airdropping to {bcolors.OKGREEN}{len(address_list)} users{bcolors.ENDC}')
print(f'Estimated total tokens to be distributed: {bcolors.OKGREEN}{(len(address_list) * drop):,f}{bcolors.ENDC}\n')
except (OSError, IOError) as e:
sys.exit(f"Error opening address list files.\n{e.strerror}")
# region Create log files, print locations, write headers
timestamp = get_current_utc_time_str()
log_success = gen_logfile(SUCCESS_LOGS, timestamp, LOG_FOLDER_PREFIX)
log_canceled = gen_logfile(CANCELED_LOGS, timestamp, LOG_FOLDER_PREFIX)
log_failed = gen_logfile(FAILED_LOGS, timestamp, LOG_FOLDER_PREFIX)
log_unconfirmed = gen_logfile(UNCONFIRMED_LOGS, timestamp, LOG_FOLDER_PREFIX)
log_full = gen_logfile(FULL_LOGS, timestamp, LOG_FOLDER_PREFIX)
print(f" Successful logs: (tail -f {log_success})")
print(f" Canceled logs: (tail -f {log_canceled})")
print(f" Failed logs: (tail -f {log_failed})")
print(f" Unconfirmed logs: (tail -f {log_unconfirmed})")
print(f" Detailed logs: (tail -f {log_full})")
with open(log_success, "a") as ls:
ls.write('recipient,amount,signature\n')
with open(log_canceled, "a") as lc:
lc.write('recipient,amount\n')
with open(log_failed, "a") as lfa:
lfa.write('recipient,amount,error\n')
with open(log_unconfirmed, "a") as lu:
lu.write('recipient,amount,error\n')
# endregion
print()
try:
continue_airdrop_prompt(interactive, SEPARATOR)
i = 0
while i < len(address_list):
addr = (address_list[i]).strip()
options = []
if fund_recipient:
options.append('--fund-recipient')
if allow_unfunded_recipient:
options.append('--allow-unfunded-recipient')
cmd = TransferCmd("spl-token", "transfer",
TOKEN_MINT, TOKEN_DECIMALS, drop, addr, RPC_URL, options)
if not interactive:
log_detail_entry = ''
print(f"{i+1}. Airdrop to {addr}: ", end="", flush=True)
log_detail_entry += f"{i+1}. Cmdline: {cmd.to_str()}\n"
log_detail_entry += try_transfer(
cmd, addr, drop,
log_success, log_unconfirmed, log_failed,
TOO_MANY_REQUESTS, RPC_ERROR, UNCONFIRMED)
with open(log_full, "a") as lf:
lf.write(log_detail_entry + LOG_SEPARATOR)
del cmd
i += 1
elif interactive:
log_detail_entry = ""
print(f"{i+1}. ", end="", flush=True)
log_detail_entry += f"{i+1}. Cmdline: {cmd.to_str()}\n"
confirm, switch_mode = single_transaction_prompt(
cmd.to_str(), drop, addr, TOKEN_DECIMALS)
if switch_mode:
print("Switching to non-interactive mode.")
interactive = False
continue
if confirm:
log_detail_entry += try_transfer(
cmd, addr, drop,
log_success, log_unconfirmed, log_failed,
TOO_MANY_REQUESTS, RPC_ERROR, UNCONFIRMED)
with open(log_full, "a") as lf:
lf.write(log_detail_entry + LOG_SEPARATOR)
elif not confirm:
print(
f"{bcolors.DANGER}CANCELED{bcolors.ENDC}", flush=True)
cancel = f"{addr},{drop:f}"
with open(log_canceled, "a") as lc:
lc.write(cancel + "\n")
log_detail_entry += f"Cancel: {cancel}\n"
with open(log_full, "a") as lf:
lf.write(log_detail_entry + LOG_SEPARATOR)
print(f"{bcolors.WARNING}{SEPARATOR}{bcolors.ENDC}")
del cmd
i += 1
except KeyboardInterrupt:
sys.exit("Interrupted, exiting.")
finally:
print("Log file handlers closed.")
print("Done!")
# region Argument parsing
parser = argparse.ArgumentParser(
description='Token distribution terminal application for transferring a fixed \
(flat) amount of tokens to given SOL or token addresses. This application can also \
be ran as a checker before and after a distribution, to check if all users \
received the expected amount of tokens. The application is dependent on Solana CLI \
tools being available on the PATH (\'solana\' and \'spl-token\').'
)
subparsers = parser.add_subparsers(
help='Select usage mode: check before a distribution, check after or run a distribution (transfer).',
dest='mode')
parser_b = subparsers.add_parser(
'check-before', help='Checker before a distribution, generates a CSV file with a snapshot of current balances of all accounts, and the expected balance after the distribution.')
parser_b.add_argument(
'-a',
'--address-list',
dest='file_name',
metavar='ADDRESS_LIST_FILE',
required=True,
help='Path to the file containing a list of addresses, seperated into new lines.'
)
parser_b.add_argument(
'-t',
'--address-type',
metavar='ADDRESS_TYPE',
dest='address_type',
choices={'token', 'owner'},
required=True,
help='Select from using token addresses or owner addresses in the input file {owner | token}.'
)
parser_b.add_argument(
'-d',
'--drop',
metavar='DROP_AMOUNT',
dest='drop',
type=float,
required=True,
help='The amount of tokens that will be distributed to each recipient.'
)
parser_a = subparsers.add_parser(
'check-after', help='Run the checker after a distribution, to check if all recipients received the expected amount of tokens.')
parser_a.add_argument(
'-t',
'--address-type',
metavar='ADDRESS_TYPE',
dest='address_type',
choices={'token', 'owner'},
required=True,
help='Select from using token addresses, or owner account addresses in the input file {token | owner}.'
)
parser_a.add_argument(
'-b',
'--before-file',
metavar='BEFORE_FILE',
dest='before_file_name',
required=True,
help='Path to the CSV file generated by the \'before\' command (before.csv).'
)
parser_t = subparsers.add_parser(
'transfer', help='Distribute a flat amount of tokens to all given addresses.')
parser_t.add_argument(
'-d',
'--drop',
dest="drop_amount",
type=float,
required=False,
help='The amount of tokens that will be distributed to each recipient.'
)
parser_t.add_argument(
'--non-interactive',
dest="interactive",
default=True,
action='store_false',
required=False,
help='Run in non-interactive mode (no confirmation prompts).'
)
parser_t.add_argument(
'-a',
'--address-list',
dest="address_list",
required=True,
help='Path to the file that contains all addresses that will receive the \
airdrop. Each address should be in a seperate line. The file must be UTF-8 encoded.'
)
parser_t.add_argument(
'--fund-recipient',
action='store_true',
required=False,
help='Create the associated token account for the recipient if it does not exist.'
)
parser_t.add_argument(
'--allow-unfunded-recipient',
action='store_true',
required=False,
help='Complete the transfer even if the recipient\'s address is not funded.'
)
parser_t.add_argument(
'--retry-on-429',
dest='retry_on_429',
action='store_true',
default=False,
required=False,
help='Retry when a HTTP 429 error code is encountered. Use this at your own risk.'
)
#endregion
if __name__ == '__main__':
TOKEN_MINT = ""
TOKEN_DECIMALS = ""
RPC_URL = ""
LOG_FOLDER_PREFIX = 'logs-'
FULL_LOGS = 'detailed.log'
SUCCESS_LOGS = 'success.log'
FAILED_LOGS = 'failed.log'
CANCELED_LOGS = 'canceled.log'
UNCONFIRMED_LOGS = 'unconfirmed.log'
RETRY_ON_429 = False
main()