-
Notifications
You must be signed in to change notification settings - Fork 0
/
funcs.py
5195 lines (4339 loc) · 188 KB
/
funcs.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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime
import json
import re
import logging
import time
import pytz
from sqlalchemy.exc import SQLAlchemyError
from functools import wraps
def log_exception(e):
logging.exception(e)
def log_error(e):
logging.error(e)
def setup_logger(name, log_file, level=logging.INFO):
handler = logging.FileHandler(log_file)
logger = logging.getLogger(name)
logger.setLevel(level)
logger.addHandler(handler)
return logger
measure_god = {}
def add_measure_god(elapsed, name):
global measure_god
if name in measure_god:
measure_god[name]['totalTime'] += elapsed
measure_god[name]['calls'] += 1
measure_god[name]['average'] = measure_god[name]['totalTime'] / measure_god[name]['calls']
else:
measure_god[name] = {
'totalTime': elapsed,
'calls': 1,
'average': elapsed
}
def measure_godding():
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
start = time.time()
rv = f(*args, **kwargs)
end = time.time()
add_measure_god(end - start, f.__name__)
return rv
return decorated_function
return decorator
def catch_and_log():
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
try:
return f(*args, **kwargs)
except SQLAlchemyError as err:
log_error('{}: {}'.format(f.__name__, err))
log_exception(err)
raise err
except Exception as err:
log_error('{}: {}'.format(f.__name__, err))
log_exception(err)
raise err
return decorated_function
return decorator
def load_transaction_basics(transaction):
new_transaction = {}
new_transaction['transaction_id'] = transaction['trx_id']
new_transaction['seq'] = transaction['global_sequence']
new_transaction['block_num'] = transaction['block_num']
new_transaction['timestamp'] = datetime.datetime.strptime(
re.sub(r'\.\d+Z', 'Z', transaction['@timestamp']), '%Y-%m-%dT%H:%M:%S.%f'
) if '@timestamp' in transaction else (transaction['timestamp'])
new_transaction['action_name'] = transaction['act']['name']
return new_transaction
def session_execute_logged(session, sql, args={}):
global measure_god
start = time.time()
res = session.execute(sql, args)
end = time.time()
elapsed = end - start
if sql in measure_god:
measure_god[sql]['totalTime'] += elapsed
measure_god[sql]['calls'] += 1
measure_god[sql]['average'] = measure_god[sql]['totalTime'] / measure_god[sql]['calls']
else:
measure_god[sql] = {
'totalTime': elapsed,
'calls': 1,
'average': elapsed
}
return res
def parse_attributes(session, collection, schema, data):
attribute_ids = []
for key in data.keys():
if key.lower() in ['name', 'img', 'title', 'video', 'unique', 'generic', 'description']:
continue
if len(key) > 64 or not key:
continue
value = data[key]
int_value = None
float_value = None
bool_value = None
if isinstance(value, bool):
bool_value = value
value = None
elif isinstance(value, int):
int_value = value
value = None
if int_value > 9223372036854775807 or int_value < -9223372036854775808:
value = str(value)
int_value = None
elif isinstance(value, float):
float_value = value
value = None
else:
value = str(value)
if len(value) > 64 or not value:
continue
res = session_execute_logged(
session,
'WITH insert_result AS (INSERT INTO attributes '
'(collection, schema, attribute_name, string_value, int_value, float_value, bool_value) '
'SELECT :collection, :schema, :key, :strvalue, :numvalue, :floatvalue, :boolvalue '
'WHERE NOT EXISTS ('
' SELECT attribute_name '
' FROM attributes '
' WHERE collection = :collection AND schema = :schema '
' AND attribute_name = :key AND {attribute_clause} '
') RETURNING attribute_id) '
'SELECT attribute_id FROM attributes '
'WHERE collection = :collection AND schema = :schema '
'AND attribute_name = :key AND {attribute_clause} '
'UNION SELECT attribute_id FROM insert_result'.format(
attribute_clause='int_value = :numvalue' if int_value or int_value == 0 else (
'float_value = :floatvalue') if float_value or float_value == 0 else (
'bool_value = :boolvalue' if bool_value or bool_value == False else 'string_value = :strvalue'
)
),
{
'collection': collection, 'schema': schema, 'key': key,
'strvalue': value, 'numvalue': int_value, 'floatvalue': float_value,
'boolvalue': bool_value
}
).first()
if res:
attribute_ids.append(res['attribute_id'])
return attribute_ids
def parse_simple_attributes(session, collection, schema, data):
attribute_ids = []
for key in data.keys():
if collection == 'ilovekolobok' and key in ['bdate', 'genome', 'cd', 'p1', 'p2', 'prize_date']:
continue
if key.lower() in ['name', 'img', 'title', 'video', 'unique', 'generic', 'description']:
continue
if len(key) > 64 or not key:
continue
value = data[key]
int_value = None
float_value = None
bool_value = None
if isinstance(value, bool):
bool_value = value
value = None
elif isinstance(value, int):
int_value = value
value = None
if int_value > 9223372036854775807 or int_value < -9223372036854775808:
value = str(value)
int_value = None
elif isinstance(value, float):
float_value = value
value = None
else:
value = str(value)
if len(value) > 64 or not value:
continue
res = session_execute_logged(
session,
'WITH insert_result AS (INSERT INTO attributes '
'(collection, schema, attribute_name, string_value, int_value, float_value, bool_value) '
'SELECT :collection, :schema, :key, :strvalue, :numvalue, :floatvalue, :boolvalue '
'WHERE NOT EXISTS ('
' SELECT attribute_name '
' FROM attributes '
' WHERE collection = :collection AND schema = :schema '
' AND attribute_name = :key AND {attribute_clause} '
') RETURNING attribute_id) '
'SELECT attribute_id FROM attributes '
'WHERE collection = :collection AND schema = :schema '
'AND attribute_name = :key AND {attribute_clause} '
'UNION SELECT attribute_id FROM insert_result'.format(
attribute_clause='int_value = :numvalue' if int_value or int_value == 0 else (
'float_value = :floatvalue') if float_value or float_value == 0 else (
'bool_value = :boolvalue' if bool_value or bool_value == False else 'string_value = :strvalue'
)
),
{
'collection': collection, 'schema': schema, 'key': key,
'strvalue': value, 'numvalue': int_value, 'floatvalue': float_value,
'boolvalue': bool_value
}
).first()
if res:
attribute_ids.append(res['attribute_id'])
return attribute_ids
def parse_data(data):
data_items = {}
for item in data:
if 'int' in item['value'][0]:
data_items[item['key']] = int(item['value'][1])
elif 'float' in item['value'][0]:
data_items[item['key']] = float(item['value'][1])
elif 'string' in item['value'][0]:
data_items[item['key']] = item['value'][1].replace("\\u0000", "").replace('\x00', '')
else:
data_items[item['key']] = str(item['value'][1])
return data_items
def construct_memo_clause(transaction):
if 'memo' in transaction and transaction['memo']:
return (
'WITH insert_result AS (INSERT INTO memos (memo) SELECT :memo WHERE NOT EXISTS ('
'SELECT memo FROM memos WHERE md5(memo) = md5(:memo)) RETURNING memo_id) '
)
return ''
def construct_with_clause(asset):
with_clause = ''
with_clauses = []
if 'image' in asset and asset['image']:
with_clauses.append(
'image_insert_result AS (INSERT INTO images (image) SELECT :image WHERE NOT EXISTS ('
'SELECT image FROM images WHERE image = :image) RETURNING image_id)'
)
if 'video' in asset and asset['video']:
with_clauses.append(
'video_insert_result AS (INSERT INTO videos (video) SELECT :video WHERE NOT EXISTS ('
'SELECT video FROM videos WHERE video = :video) RETURNING video_id)'
)
if 'name' in asset and asset['name']:
with_clauses.append(
'name_insert_result AS (INSERT INTO names (name) SELECT :name WHERE NOT EXISTS ('
'SELECT name FROM names WHERE name = :name) RETURNING name_id)'
)
if 'idata' in asset and asset['idata'] and asset['idata'] != '{}':
with_clauses.append(
'idata_insert_result AS (INSERT INTO data (data) SELECT :idata WHERE NOT EXISTS ('
'SELECT data FROM data WHERE md5(data) = md5(:idata)) RETURNING data_id)'
)
if 'mdata' in asset and asset['mdata'] and asset['mdata'] != '{}' and (
'idata' not in asset or asset['mdata'] != asset['idata']):
with_clauses.append(
'mdata_insert_result AS (INSERT INTO data (data) SELECT :mdata WHERE NOT EXISTS ('
'SELECT data FROM data WHERE md5(data) = md5(:mdata)) RETURNING data_id)'
)
if len(with_clauses) > 0:
with_clause = 'WITH ' + ', '.join(with_clauses)
return with_clause
def construct_mdata_column(asset):
if asset['mdata'] and asset['mdata'] != '{}' and (
'idata' not in asset or asset['mdata'] != asset['idata']
):
return (
'(SELECT data_id FROM data WHERE md5(data) = md5(:mdata) UNION SELECT data_id FROM mdata_insert_result)'
)
elif 'idata' in asset and asset['idata'] and asset['idata'] != '{}' and asset['mdata'] == asset['idata']:
return (
'(SELECT data_id FROM data WHERE md5(data) = md5(:mdata) UNION SELECT data_id FROM idata_insert_result)'
)
else:
return 'NULL'
def _parse_mdata(asset):
try:
return json.loads(asset['mdata'].replace('\\', '').replace('\"{', '{').replace('}\"', '}').replace('""', '","').replace('”', '"')) if asset['mdata'] else None
except ValueError:
return {'mdata': asset['mdata']}
def _parse_idata(asset):
try:
return json.loads(asset['idata'].replace('\\', '').replace('\"{', '{').replace('}\"', '}').replace('""', '","').replace('”', '"')) if asset['idata'] else None
except ValueError:
return {'idata': asset['idata']}
def _get_data(trx):
act = trx['act']
return json.loads(act['data']) if isinstance(act['data'], str) else act['data']
def _get_name(asset):
mdata = _parse_mdata(asset)
idata = _parse_idata(asset)
name = None
title = None
if mdata and isinstance(mdata, dict) and 'name' in mdata.keys():
name = mdata['name']
if mdata and isinstance(mdata, dict) and 'title' in mdata.keys():
title = mdata['title']
if idata and isinstance(idata, dict) and 'name' in idata.keys():
name = idata['name']
if name and title:
return '{} - {}'.format(name, title)
if name:
return name
if title:
return title
return None
def _get_image(asset):
mdata = _parse_mdata(asset)
idata = _parse_idata(asset)
img = mdata['img'] if mdata and isinstance(mdata, dict) and 'img' in mdata.keys() else None
if not img:
img = idata['img'] if idata and isinstance(idata, dict) and 'img' in idata.keys() else None
return img
def _get_video(asset):
mdata = _parse_mdata(asset)
idata = _parse_idata(asset)
img = mdata['video'] if mdata and isinstance(mdata, dict) and 'video' in mdata.keys() else None
if not img:
img = idata['video'] if idata and isinstance(idata, dict) and 'video' in idata.keys() else None
return img
def _insert_transfer(session, transaction):
with_clause = construct_memo_clause(transaction)
session_execute_logged(
session,
'{with_clause} '
'INSERT INTO transfers '
'(asset_ids, seq, block_num, timestamp, sender, receiver, memo_id) '
'SELECT :asset_ids, :seq, :block_num, :timestamp, :sender, :receiver, '
'{memo_column} '
'WHERE NOT EXISTS (SELECT seq FROM transfers WHERE seq = :seq)'.format(
with_clause=with_clause,
memo_column=(
'(SELECT memo_id FROM memos WHERE md5(memo) = md5(:memo) UNION SELECT memo_id FROM insert_result)'
) if 'memo' in transaction and transaction['memo'] else 'NULL'
),
transaction
)
if len(transaction['asset_ids']) == 0:
return
for asset_id in transaction['asset_ids']:
session_execute_logged(
session,
'UPDATE assets SET owner = :receiver, transferred = :timestamp WHERE asset_id = :asset_id ', {
'receiver': transaction['receiver'],
'timestamp': transaction['timestamp'],
'asset_id': asset_id,
'seq': transaction['seq']
}
)
if transaction['receiver'] in ['waxdaofarmer', 'pepperstake']:
try:
for asset_id in transaction['asset_ids']:
transaction['asset_id'] = asset_id
session_execute_logged(
session,
'INSERT INTO stakes ('
' asset_id, stake_contract, staker, memo, seq, block_num, timestamp '
') '
'SELECT :asset_id, :receiver, :sender, :memo, :seq, :block_num, :timestamp ',
transaction
)
except SQLAlchemyError as err:
log_error('_insert_transfer: {}'.format(err))
raise err
except Exception as err:
log_error('_insert_transfer: {}'.format(err))
raise err
elif transaction['sender'] in ['waxdaofarmer', 'pepperstake']:
for asset_id in transaction['asset_ids']:
transaction['asset_id'] = asset_id
session_execute_logged(
session,
'INSERT INTO removed_stakes ('
' asset_id, stake_contract, staker, memo, seq, block_num, timestamp, removed_seq, removed_block_num '
') '
'SELECT asset_id, stake_contract, staker, memo, seq, block_num, timestamp, :seq, :block_num '
'FROM stakes WHERE asset_id = :asset_id ',
transaction
)
session_execute_logged(
session,
'DELETE FROM stakes '
'WHERE asset_id = :asset_id ',
transaction
)
if transaction['receiver'] == 'simplemarket':
try:
try:
memo_dict = json.loads(transaction['memo'])
except Exception as err:
return
if 'price' not in memo_dict:
return
price_tag = memo_dict['price']
price = float(price_tag.split(' ')[0])
currency = price_tag.split(' ')[1]
transaction['price'] = price
transaction['currency'] = currency
session_execute_logged(
session,
'INSERT INTO listings ('
' asset_ids, collection, seller, market, maker, price, currency, listing_id, seq, block_num, '
' timestamp, estimated_wax_price '
') '
'SELECT array_agg(asset_id) AS asset_ids, collection, :sender, :receiver, NULL, :price, :currency, '
'asset_id, :seq, :block_num, :timestamp, CASE WHEN :currency = \'WAX\' THEN :price '
'ELSE :price * (SELECT usd FROM usd_prices ORDER BY timestamp DESC LIMIT 1) END '
'FROM ('
' SELECT unnest(:asset_ids) AS asset_id '
') t LEFT JOIN assets a USING(asset_id) '
'GROUP BY asset_id, collection ',
transaction
)
except SQLAlchemyError as err:
log_error('_insert_transfer: {}'.format(err))
raise err
except Exception as err:
log_error('_insert_transfer: {}'.format(err))
raise err
elif transaction['sender'] == 'simplemarket' and transaction['seq'] < 429078747:
try:
for asset_id in transaction['asset_ids']:
transaction['asset_id'] = asset_id
session_execute_logged(
session,
'INSERT INTO removed_simplemarket_listings '
'SELECT l.*, :seq, :block_num FROM listings l '
'WHERE market = \'simplemarket\' AND l.listing_id = :asset_id '
'AND NOT EXISTS (SELECT sale_id FROM removed_simplemarket_listings WHERE sale_id = l.sale_id)',
transaction
)
session.commit()
session_execute_logged(
session,
'INSERT INTO sales '
'SELECT l.asset_ids, a.collection, seller, :receiver, '
'CASE WHEN currency = \'WAX\' THEN price ELSE price / ('
' SELECT usd FROM usd_prices WHERE timestamp < :timestamp ORDER BY timestamp DESC LIMIT 1'
') END, CASE WHEN currency = \'USD\' THEN price ELSE price * ('
' SELECT usd FROM usd_prices WHERE timestamp < :timestamp ORDER BY timestamp DESC LIMIT 1'
') END, currency, :asset_id, l.market, NULL, NULL, :seq, :block_num, :timestamp '
'FROM listings l LEFT JOIN assets a ON asset_id = asset_ids[1] '
'WHERE market = \'simplemarket\' AND :asset_id = l.listing_id ',
transaction
)
session.commit()
session_execute_logged(
session,
'DELETE FROM listings l WHERE sale_id IN ('
' SELECT sale_id FROM removed_simplemarket_listings WHERE removed_seq = :seq'
')',
transaction
)
except SQLAlchemyError as err:
log_error('_insert_transfer: {}'.format(err))
raise err
except Exception as err:
log_error('_insert_transfer: {}'.format(err))
raise err
@catch_and_log()
def load_drop(session, update, contract):
new_drop = load_transaction_basics(update)
data = _get_data(update)
if 'drop_id' not in data or ('assets_to_mint' not in data and 'templates_to_mint' not in data and 'attributes' not in data):
return
new_drop['drop_id'] = data['drop_id']
new_drop['collection'] = data['collection_name']
new_drop['collection_name'] = data['collection_name']
new_drop['display_data'] = data['display_data'] if 'display_data' in data else None
new_drop['fee_rate'] = data['fee_rate'] if 'fee_rate' in data else 0
new_drop['account_limit'] = data['account_limit'] if 'account_limit' in data else 0
new_drop['account_limit_cooldown'] = data['account_limit_cooldown'] if 'account_limit_cooldown' in data else 0
new_drop['max_claimable'] = data['max_claimable']
new_drop['start_time'] = datetime.datetime.fromtimestamp(data['start_time']) if 'start_time' in data and data[
'start_time'] else None
new_drop['end_time'] = datetime.datetime.fromtimestamp(data['end_time']) if 'end_time' in data and data[
'end_time'] else None
new_drop['num_claimed'] = 0
new_drop['auth_required'] = data['auth_required'] if 'auth_required' in data else False
new_drop['is_hidden'] = data['is_hidden'] if 'is_hidden' in data else False
new_drop['contract'] = contract
new_drop['templates_to_mint'] = []
new_drop['benefit_id'] = data['benefit_id'] if 'benefit_id' in data else None
new_drop['game_id'] = data['game_id'] if 'game_id' in data else None
if 'attributes' in data:
new_drop['attributes'] = data['attributes']
new_drop['blacklist'] = data['attributes'] if 'attributes' in data else None
new_drop['name_pattern'] = data['name_pattern'] if 'name_pattern' in data else None
new_drop['template_id'] = data['template_id'] if 'template_id' in data else None
if 'assets_to_mint' in data:
for asset in data['assets_to_mint']:
new_drop['templates_to_mint'].append(asset['template_id'])
elif 'templates_to_mint' in data:
for template in data['templates_to_mint']:
new_drop['templates_to_mint'].append(template)
elif 'template_id' in data:
new_drop['templates_to_mint'].append(data['template_id'])
new_drop['price'] = None
new_drop['currency'] = None
if 'settlement_symbol' not in data or '0,NULL' == data['settlement_symbol']:
new_drop['price'] = 0
new_drop['currency'] = None
else:
lp = data['listing_price'].split(' ')
new_drop['price'] = float(lp[0])
new_drop['currency'] = lp[1]
if 'attributes' in new_drop:
attributes = {'attributes': new_drop['attributes']}
if new_drop['blacklist']:
new_drop['blacklist'] = json.dumps({'blacklist': new_drop['blacklist']})
new_drop['attributes'] = json.dumps(attributes)
session_execute_logged(
session,
'INSERT INTO pfp_drop_data (drop_id, contract, attributes, name_pattern) '
'SELECT :drop_id, :contract, :attributes, :name_pattern '
'WHERE NOT EXISTS ('
' SELECT drop_id, contract FROM pfp_drop_data WHERE drop_id = :drop_id AND contract = :contract'
') ',
new_drop
)
if 'alternative_prices' in data:
prices = [{
'price': new_drop['price'],
'currency': new_drop['currency']
}]
currencies = [new_drop['currency']]
for price in data['alternative_prices']:
prices.append({
'price': float(price.split(' ')[0]),
'currency': price.split(' ')[1]
})
currencies.append(price.split(' ')[1])
new_drop['prices'] = json.dumps(prices)
new_drop['currencies'] = currencies
session_execute_logged(
session,
'INSERT INTO drop_log_prices ('
' drop_id, contract, prices, currencies, seq, block_num, timestamp'
') '
'SELECT :drop_id, :contract, :prices, :currencies, :seq, :block_num, :timestamp '
'WHERE NOT EXISTS (SELECT seq FROM drop_log_prices WHERE seq = :seq) ', new_drop
)
session_execute_logged(
session,
'INSERT INTO drops (drop_id, collection, price, currency, fee, display_data, '
'start_time, end_time, max_claimable, num_claimed, contract, posted, seq, block_num,'
'templates_to_mint, auth_required, is_hidden, timestamp, account_limit, account_limit_cooldown) '
'SELECT :drop_id, :collection, :price, :currency, :fee_rate, :display_data, :start_time, :end_time, '
':max_claimable, :num_claimed, :contract, FALSE, :seq, :block_num, :templates_to_mint, '
':auth_required, :is_hidden, :timestamp, :account_limit, :account_limit_cooldown '
'WHERE NOT EXISTS (SELECT seq FROM drops WHERE seq = :seq) ',
new_drop
)
if new_drop['benefit_id'] and new_drop['game_id']:
session_execute_logged(
session,
'INSERT INTO twitch_drops (drop_id, contract, seq, block_num, benefit_id, game_id) '
'SELECT :drop_id, :contract, :seq, :block_num, :benefit_id, :game_id '
'WHERE NOT EXISTS (SELECT seq FROM twitch_drops WHERE seq = :seq) ',
new_drop
)
session.commit()
@catch_and_log()
def load_drop_update(session, update, contract):
data = _get_data(update)
drop = load_transaction_basics(update)
drop['display_data'] = data['display_data']
drop['drop_id'] = data['drop_id']
drop['contract'] = contract
session_execute_logged(
session,
'INSERT INTO drop_display_updates '
'(seq, timestamp, block_num, contract, drop_id, new_display_data, old_display_data) '
'SELECT :seq, :timestamp, :block_num, :contract, :drop_id, :display_data, (SELECT display_data '
'FROM drops WHERE drop_id = :drop_id AND contract = :contract) '
'WHERE NOT EXISTS (SELECT seq FROM drop_display_updates WHERE seq = :seq) ',
drop
)
session.commit()
session_execute_logged(
session,
'UPDATE drops d SET display_data = dd.new_display_data '
'FROM drop_display_updates dd '
'WHERE dd.seq = :seq AND d.drop_id = dd.drop_id AND d.contract = dd.contract',
drop
)
@catch_and_log()
def load_drop_limit_update(session, update, contract):
data = _get_data(update)
drop = load_transaction_basics(update)
drop['account_limit'] = data['account_limit']
drop['account_limit_cooldown'] = int(data['account_limit_cooldown'])
drop['drop_id'] = data['drop_id']
drop['contract'] = contract
session_execute_logged(
session,
'INSERT INTO drop_limit_updates ('
' seq, timestamp, block_num, contract, drop_id, new_account_limit, new_account_limit_cooldown, '
' old_account_limit, old_account_limit_cooldown'
') '
'SELECT :seq, :timestamp, :block_num, :contract, :drop_id, :account_limit, '
':account_limit_cooldown, '
'(SELECT account_limit FROM drops WHERE drop_id = :drop_id AND contract = :contract), '
'(SELECT account_limit_cooldown FROM drops WHERE drop_id = :drop_id AND contract = :contract) '
'WHERE NOT EXISTS (SELECT seq FROM drop_limit_updates WHERE seq = :seq) ',
drop
)
session.commit()
session_execute_logged(
session,
'UPDATE drops d '
'SET account_limit = new_account_limit, '
'account_limit_cooldown = new_account_limit_cooldown '
'FROM drop_limit_updates dl '
'WHERE dl.seq = :seq AND d.drop_id = dl.drop_id AND d.contract = dl.contract ',
drop
)
@catch_and_log()
def load_drop_max_update(session, update, contract):
data = _get_data(update)
drop = load_transaction_basics(update)
drop['max_claimable'] = data['new_max_claimable']
drop['drop_id'] = data['drop_id']
drop['contract'] = contract
if len(drop['max_claimable']) > 19 and int(drop['max_claimable']) > 9223372036854775807:
drop['max_claimable'] = 9223372036854775807
session_execute_logged(
session,
'INSERT INTO drop_max_updates '
'(seq, timestamp, block_num, contract, drop_id, new_max_claimable, old_max_claimable) '
'SELECT :seq, :timestamp, :block_num, :contract, :drop_id, :max_claimable, '
'(SELECT max_claimable FROM drops WHERE drop_id = :drop_id AND contract = :contract) '
'WHERE NOT EXISTS (SELECT seq FROM drop_max_updates WHERE seq = :seq) ',
drop
)
session.commit()
session_execute_logged(
session,
'UPDATE drops d SET max_claimable = du.new_max_claimable '
'FROM drop_max_updates du '
'WHERE du.seq = :seq AND d.drop_id = du.drop_id AND d.contract = du.contract',
drop
)
@catch_and_log()
def load_drop_price_update(session, update, contract):
data = _get_data(update)
drop = load_transaction_basics(update)
drop['drop_id'] = data['drop_id']
drop['contract'] = contract
listing_price_key = 'listing_prices'
if listing_price_key not in data:
listing_price_key = 'listing_price'
if '0 NULL' == data[listing_price_key]:
drop['price'] = 0
drop['currency'] = None
else:
lp = data[listing_price_key].split(' ')
drop['price'] = float(lp[0])
drop['currency'] = lp[1]
if 'alternative_prices' in data:
prices = [{
'price': drop['price'],
'currency': drop['currency']
}]
currencies = [drop['currency']]
for price in data['alternative_prices']:
prices.append({
'price': float(price.split(' ')[0]),
'currency': price.split(' ')[1]
})
currencies.append(price.split(' ')[1])
drop['prices'] = json.dumps(prices)
drop['currencies'] = currencies
session_execute_logged(
session,
'INSERT INTO drop_log_prices ('
' drop_id, contract, prices, currencies, seq, block_num, timestamp'
') '
'SELECT :drop_id, :contract, :prices, :currencies, :seq, :block_num, :timestamp '
'WHERE NOT EXISTS (SELECT seq FROM drop_log_prices WHERE seq = :seq) ', drop)
session_execute_logged(
session,
'INSERT INTO drop_price_updates '
'(seq, timestamp, block_num, contract, drop_id, new_price, new_currency, old_price, old_currency) '
'SELECT :seq, :timestamp, :block_num, :contract, :drop_id, :price, :currency, '
'(SELECT price FROM drops WHERE drop_id = :drop_id AND contract = :contract), '
'(SELECT currency FROM drops WHERE drop_id = :drop_id AND contract = :contract) '
'WHERE NOT EXISTS (SELECT seq FROM drop_price_updates WHERE seq = :seq) ',
drop
)
session.commit()
session_execute_logged(
session,
'UPDATE drops d SET price = du.new_price, currency = du.new_currency '
'FROM drop_price_updates du '
'WHERE du.seq = :seq AND d.drop_id = du.drop_id AND d.contract = du.contract',
drop
)
@catch_and_log()
def load_drop_prices_update(session, update, contract='nfthivedrops'):
data = _get_data(update)
drop = load_transaction_basics(update)
drop['drop_id'] = data['drop_id']
drop['contract'] = contract
listing_prices = data['listing_prices']
listing_price = listing_prices[0]
if len(listing_price) == 1:
listing_price = listing_prices
if '0 NULL' == listing_price:
drop['price'] = 0
drop['currency'] = None
else:
lp = listing_price.split(' ')
drop['price'] = float(lp[0])
drop['currency'] = lp[1]
session_execute_logged(
session,
'INSERT INTO drop_price_updates '
'(seq, timestamp, block_num, contract, drop_id, new_price, new_currency, old_price, old_currency) '
'SELECT :seq, :timestamp, :block_num, :contract, :drop_id, :price, :currency, '
'(SELECT price FROM drops WHERE drop_id = :drop_id AND contract = :contract), '
'(SELECT currency FROM drops WHERE drop_id = :drop_id AND contract = :contract) '
'WHERE NOT EXISTS (SELECT seq FROM drop_price_updates WHERE seq = :seq) ',
drop
)
session.commit()
session_execute_logged(
session,
'UPDATE drops d SET price = du.new_price, currency = du.new_currency '
'FROM drop_price_updates du '
'WHERE du.seq = :seq AND d.drop_id = du.drop_id AND d.contract = du.contract',
drop
)
@catch_and_log()
def load_drop_fee_rate(session, update, contract):
data = _get_data(update)
drop = load_transaction_basics(update)
drop['fee_rate'] = data['fee_rate'] if 'fee_rate' in data else data['fee']
drop['drop_id'] = data['drop_id']
drop['contract'] = contract
session_execute_logged(
session,
'INSERT INTO drop_fee_updates (seq, timestamp, block_num, contract, drop_id, new_fee_rate, old_fee_rate) '
'SELECT :seq, :timestamp, :block_num, :contract, :drop_id, :fee_rate, '
'(SELECT fee FROM drops WHERE drop_id = :drop_id AND contract = :contract) '
'WHERE NOT EXISTS (SELECT seq FROM drop_fee_updates WHERE seq = :seq) ',
drop
)
session.commit()
session_execute_logged(
session,
'UPDATE drops d SET fee = du.new_fee_rate '
'FROM drop_fee_updates du '
'WHERE du.seq = :seq AND d.drop_id = du.drop_id AND d.contract = du.contract',
drop
)
@catch_and_log()
def load_drop_drop_auth(session, update, contract):
data = _get_data(update)
drop = load_transaction_basics(update)
drop['auth_required'] = data['auth_required']
drop['drop_id'] = data['drop_id']
drop['contract'] = contract
session_execute_logged(
session,
'INSERT INTO drop_auth_updates (seq, timestamp, block_num, contract, drop_id, new_auth_required, '
'old_auth_required) '
'SELECT :seq, :timestamp, :block_num, :contract, :drop_id, :auth_required, '
'(SELECT auth_required FROM drops WHERE drop_id = :drop_id AND contract = :contract) '
'WHERE NOT EXISTS (SELECT seq FROM drop_auth_updates WHERE seq = :seq) ',
drop
)
session.commit()
session_execute_logged(
session,
'UPDATE drops d SET auth_required = du.new_auth_required '
'FROM drop_auth_updates du '
'WHERE du.seq = :seq AND d.drop_id = du.drop_id AND d.contract = du.contract',
drop
)
@catch_and_log()
def load_drop_hidden(session, update, contract):
data = _get_data(update)
drop = load_transaction_basics(update)
drop['is_hidden'] = data['is_hidden']
drop['drop_id'] = data['drop_id']
drop['contract'] = contract
session_execute_logged(
session,
'INSERT INTO drop_hidden_updates '
'(seq, timestamp, block_num, contract, drop_id, new_is_hidden, old_is_hidden) '
'SELECT :seq, :timestamp, :block_num, :contract, :drop_id, :is_hidden, '
'(SELECT is_hidden FROM drops WHERE drop_id = :drop_id AND contract = :contract) '
'WHERE NOT EXISTS (SELECT seq FROM drop_hidden_updates WHERE seq = :seq) ',
drop
)
session.commit()
session_execute_logged(
session,
'UPDATE drops d SET is_hidden = du.new_is_hidden '
'FROM drop_hidden_updates du '
'WHERE du.seq = :seq AND d.drop_id = du.drop_id AND d.contract = du.contract',
drop
)
@catch_and_log()
def load_drop_times_update(session, update, contract):
data = _get_data(update)
drop = load_transaction_basics(update)
if 'start_time' not in data or 'end_time' not in data:
return
drop['start_time'] = datetime.datetime.fromtimestamp(data['start_time']) if data['start_time'] else None
drop['end_time'] = datetime.datetime.fromtimestamp(data['end_time']) if data['end_time'] else None
drop['drop_id'] = data['drop_id']
drop['contract'] = contract
session_execute_logged(
session,
'INSERT INTO drop_times_updates '
'(seq, timestamp, block_num, contract, drop_id, new_start_time, new_end_time, old_start_time, '
'old_end_time) '
'SELECT :seq, :timestamp, :block_num, :contract, :drop_id, :start_time, :end_time, '
'(SELECT start_time FROM drops WHERE drop_id = :drop_id AND contract = :contract), '
'(SELECT end_time FROM drops WHERE drop_id = :drop_id AND contract = :contract) '
'WHERE NOT EXISTS (SELECT seq FROM drop_times_updates WHERE seq = :seq) ',
drop
)
session.commit()
session_execute_logged(
session,
'UPDATE drops d SET start_time = du.new_start_time, end_time = du.new_end_time '
'FROM drop_times_updates du '
'WHERE du.seq = :seq AND d.drop_id = du.drop_id AND d.contract = du.contract',
drop
)
@catch_and_log()
def load_claim_drop(session, transfer, contract):
try:
data = _get_data(transfer)
if 'drop_id' not in data:
return
new_transfer = load_transaction_basics(transfer)
new_transfer['claimer'] = data['claimer']
new_transfer['drop_id'] = data['drop_id']
new_transfer['amount'] = data['claim_amount'] if 'claim_amount' in data else data['amount'] if 'amount' in data else 1
new_transfer['wax_usd'] = int(data['intended_delphi_median']) * 0.0001 if 'intended_delphi_median' in data else 0
new_transfer['contract'] = contract
new_transfer['country'] = data['country'][0:11] if 'country' in data else None
new_transfer['referrer'] = data['referrer'][0:11] if 'referrer' in data else None
new_transfer['currency'] = data['currency'][0:11].replace("\x00", "") if 'currency' in data and data['currency'] else None
new_transfer['benefit_id'] = data['benefit_id'] if 'benefit_id' in data else None
new_transfer['reward_id'] = data['reward_id'] if 'reward_id' in data else None
new_transfer['reward_string'] = data['reward_string'] if 'reward_string' in data else None
session_execute_logged(
session,
'INSERT INTO drop_claims ('
' drop_id, contract, claimer, country, referrer, amount, currency, seq, block_num, timestamp'
') '
'SELECT :drop_id, :contract, :claimer, :country, :referrer, :amount, :currency, :seq, :block_num, :timestamp '
'WHERE NOT EXISTS (SELECT seq FROM drop_claims WHERE seq = :seq)',
new_transfer