-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogic.py
3223 lines (2822 loc) · 131 KB
/
logic.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 concurrent
import datetime
import json
from sqlalchemy.exc import SQLAlchemyError
from api import logging
from api import cache
from api import executor
from api import db
DATE_FORMAT_STRING = "%Y-%m-%d %H:%M:%S"
DATE_FROM_STRING_FORMAT = "%Y-%m-%dT%H:%M:%S%z"
DATE_FROM_STRING_SPLIT_FORMAT = "%Y-%m-%dT%H:%M:%S"
def create_session():
return db.session
def _format_video(video):
if 'http' in video:
return video
return 'https://ipfs.hivebp.io/ipfs/{}'.format(video.replace('video:', '').strip())
def _format_image(image):
if image and 'http' not in image and 'video:' not in image:
return 'https://ipfs.hivebp.io/ipfs/{}'.format(image)
return image if image else ''
def _format_thumbnail(image):
if not image:
return image
if 'video:' in image:
return 'https://ipfs.hivebp.io/video?hash={}'.format(
image.replace('DUNGEONS-&-DRAGONS', 'DUNGEONS-%26-DRAGONS').replace('video:', '').strip())
else:
return 'https://ipfs.hivebp.io/thumbnail?hash={}'.format(
image.replace('DUNGEONS-&-DRAGONS', 'DUNGEONS-%26-DRAGONS'))
def _format_collection_thumbnail(collection, image=None, size=80):
if not image:
return image
return 'https://ipfs.hivebp.io/preview?collection={}&size={}&hash={}'.format(
collection, size, image.replace('video:', '').replace('DUNGEONS-&-DRAGONS', 'DUNGEONS-%26-DRAGONS').strip()
)
def _format_preview(image):
return 'https://ipfs.hivebp.io/preview/{}'.format(image)
def _format_banner(image):
return 'https://ipfs.hivebp.io/nfthive?ipfs={}'.format(image)
def _parse_mdata(asset):
return json.loads(asset.mdata.replace('""', '","').replace('”', '"')) if asset.mdata else None
def _get_name(asset):
mdata = _parse_mdata(asset)
return mdata['name'] if mdata and 'name' in mdata.keys() else None
def _get_image(asset):
mdata = _parse_mdata(asset)
return mdata['img'] if mdata and 'img' in mdata.keys() else None
def to_camel_case(snake_str):
return "".join(x.capitalize() for x in snake_str.lower().split("_"))
def to_lower_camel_case(snake_str):
camel_string = to_camel_case(snake_str)
return snake_str[0].lower() + camel_string[1:]
def _format_object(item):
if isinstance(item, dict):
new_item = {}
for key in item.keys():
val = item[key]
if hasattr(val, "__len__") and not isinstance(val, str) and not isinstance(val, dict):
new_item[to_lower_camel_case(key)] = []
for e in val:
obj = _format_object(e)
if obj:
new_item[to_lower_camel_case(key)].append(obj)
elif val or val == 0:
new_item[to_lower_camel_case(key)] = _format_object(val)
elif hasattr(item, "__len__") and not isinstance(item, str):
new_item = []
for e in item:
obj = _format_object(e)
if obj:
new_item.append(obj)
else:
return item
return new_item
def _get_templates_object():
return (
'array_agg(json_build_object(\'template_id\', t.template_id, \'name\', tn.name, \'collection\', t.collection, '
'\'schema\', t.schema, \'immutable_data\', td.data, \'image\', ti.image, \'video\', tv.video, '
'\'avg_wax_price\', ts.avg_wax_price, \'avg_usd_price\', ts.avg_usd_price, '
'\'last_sold_wax\', ts.last_sold_wax, \'last_sold_usd\', ts.last_sold_usd, '
'\'last_sold_listing_id\', last_sold_listing_id, \'last_sold_timestamp\', ts.last_sold_timestamp, '
'\'floor_price\', fp.floor_price, \'num_burned\', tm.num_burned, \'num_minted\', tm.num_minted, '
'\'volume_wax\', ts.volume_wax, \'volume_usd\', ts.volume_usd, \'num_sales\', ts.num_sales, '
'\'created_at\', t.timestamp, \'block_num\', t.block_num, \'created_seq\', t.seq, '
'\'traits\', {attributes_obj})) AS templates '.format(
attributes_obj=_get_template_attributes_object()
)
)
def _get_assets_object():
return (
'array_agg(json_build_object(\'asset_id\', a.asset_id, \'name\', n.name, \'collection\', a.collection, '
'\'contract\', a.contract, \'verified\', col.verified, \'blacklisted\', col.blacklisted, '
'\'collection_image\', ci.image, \'display_name\', cn.name, \'schema\', a.schema, \'mutable_data\', m.data, '
'\'immutable_data\', i.data, \'template_immutable_data\', td.data, \'num_burned\', tm.num_burned, '
'\'avg_wax_price\', ts.avg_wax_price, \'avg_usd_price\', ts.avg_usd_price, \'last_sold_wax\', ts.last_sold_wax,'
' \'last_sold_usd\', ts.last_sold_usd, \'last_sold_listing_id\', last_sold_listing_id, '
'\'last_sold_timestamp\', ts.last_sold_timestamp, '
'\'owner\', a.owner, \'burned\', burned, \'floor_price\', fp.floor_price, \'rwax_symbol\', rt.symbol, '
'\'rwax_contract\', rt.contract, \'rwax_max_assets\', rt.max_assets, \'trait_factors\', rt.trait_factors, '
'\'rwax_decimals\', rt.decimals, \'rwax_token_name\', rt.token_name, \'rwax_supply\', rt.maximum_supply, '
'\'rwax_token_logo\', rt.token_logo, \'rwax_token_logo_lg\', rt.token_logo_lg, \'volume_wax\', ts.volume_wax, '
'\'volume_usd\', ts.volume_usd, \'num_sales\', ts.num_sales, \'num_minted\', tm.num_minted, '
'\'favorited\', f.user_name IS NOT NULL, \'template_id\', t.template_id, \'image\', img.image, '
'\'video\', vid.video, \'mint\', a.mint, \'mint_timestamp\', a.timestamp, \'mint_block_num\', a.block_num, '
'\'mint_seq\', a.seq, \'rarity_score\', p.rarity_score, \'num_traits\', p.num_traits, \'rank\', p.rank, '
'\'burnable\', a.burnable, \'transferable\', a.transferable, \'rwax_amount\', rtt.amount, '
'\'traits\', {attributes_obj})) AS assets '.format(
attributes_obj=_get_attributes_object()
)
)
def _get_badges_object(prefix='a.'):
return (
'(SELECT array_agg(json_build_object(\'name\', b.name, \'level\', b.level, \'value\', b.value, '
'\'timestamp\', b.timestamp)) FROM badges b WHERE collection = {}collection) AS badges '.format(prefix)
)
def _get_tags_object(prefix='a.'):
return (
'(SELECT array_agg(json_build_object(\'tag_id\', tg.tag_id, \'tag_name\', tg.tag_name)) '
'FROM tags_mv tg WHERE collection = {}collection) AS tags '.format(prefix)
)
def _get_attributes_object():
return (
'(SELECT array_agg(json_build_object(\'attribute_id\', attribute_id, '
'\'attribute_name\', attribute_name, \'string_value\', string_value, \'int_value\', int_value, '
'\'float_value\', float_value, \'bool_value\', bool_value, \'floor_price\', floor_wax, '
'\'rarity_score\', rarity_score, \'total_schema\', total_schema)) '
'FROM assets '
'INNER JOIN attributes ON attribute_id = ANY(attribute_ids) '
'LEFT JOIN attribute_stats USING(attribute_id) '
'WHERE asset_id = a.asset_id) '
)
def _get_listings_object():
return (
'(SELECT array_agg(json_build_object(\'listing_id\', listing_id, \'market\', market, '
'\'asset_ids\', asset_ids, \'price\', price, \'currency\', currency, \'seller\', seller)) '
'FROM listings l '
'WHERE l.collection = a.collection AND seller = owner AND a.asset_id = ANY(asset_ids) ) '
)
def _get_template_attributes_object(prefix='t.'):
return (
'(SELECT array_agg(json_build_object(\'attribute_id\', attribute_id, '
'\'attribute_name\', attribute_name, \'string_value\', string_value, \'int_value\', int_value, '
'\'float_value\', float_value, \'bool_value\', bool_value, \'floor_price\', floor_wax, '
'\'rarity_score\', rarity_score, \'total_schema\', total_schema)) '
'FROM templates '
'INNER JOIN attributes ON attribute_id = ANY(attribute_ids) '
'LEFT JOIN attribute_stats USING(attribute_id) '
'WHERE template_id = {prefix}template_id) '.format(prefix=prefix)
)
def isfloat(value):
try:
float(value)
return True
except ValueError:
return False
def construct_category_clause(
session, format_dict, collection, schema, attributes, prefix
):
category_clause = ''
attribute_ids = []
if attributes:
attr_arr = attributes.split(',')
for attr in attr_arr:
key = attr.split(':')[0]
value = attr.split(':')[1]
attr_sql = 'SELECT schema, attribute_id FROM attributes WHERE collection = :collection '
attr_dict = {
'collection': collection
}
if schema and ',' in schema:
attr_dict['schemas'] = tuple(schema.split(','))
attr_sql += ' AND schema IN :schemas'
elif schema:
attr_dict['schema'] = schema
attr_sql += ' AND schema = :schema'
attr_dict['attribute_name'] = key
use_range = False
val1 = value
val2 = value
if isinstance(value, bool) or value in ['f', 't']:
column = 'bool_value'
elif isinstance(value, int) or value.isnumeric():
column = 'int_value'
value = int(value)
if value > 9223372036854775807 or value < -9223372036854775808:
value = str(value)
column = 'string_value'
elif isinstance(value, float) or isfloat(value):
column = 'float_value'
value = float(value)
elif '-' in value and value.split('-')[0].isnumeric() and value.split('-')[1].isnumeric():
column = 'int_value'
use_range = True
val1 = int(value.split('-')[0])
val2 = int(value.split('-')[1])
elif '-' in value and isfloat(value.split('-')[0].isnumeric()) and isfloat(value.split('-')[1].isnumeric()):
column = 'float_value'
use_range = True
val1 = float(value.split('-')[0])
val2 = float(value.split('-')[1])
else:
column = 'string_value'
if use_range:
attr_sql += ' AND attribute_name = :attribute_name AND {column} BETWEEN :val1 AND :val2 '.format(
column=column
)
attr_dict['val1'] = val1
attr_dict['val2'] = val2
else:
attr_sql += ' AND attribute_name = :attribute_name AND {column} = :value '.format(column=column)
attr_dict['value'] = value
res = session.execute(attr_sql, attr_dict)
if use_range and res.rowcount > 1:
range_attribute_ids = []
for attribute in res:
range_attribute_ids.append(attribute['attribute_id'])
if len(range_attribute_ids) > 1:
category_clause += ' AND :range_attribute_ids_{} && {}attribute_ids '.format(
key, prefix
)
format_dict['range_attribute_ids_{}'.format(key)] = range_attribute_ids
elif len(range_attribute_ids) == 1:
attribute_ids.append(range_attribute_ids[0])
else:
for attribute in res:
attribute_ids.append(attribute['attribute_id'])
if len(attribute_ids) > 1:
category_clause += ' AND :attribute_ids <@ {}attribute_ids '.format(
prefix
)
format_dict['attribute_ids'] = attribute_ids
elif len(attribute_ids) == 1:
category_clause += ' AND :attribute_id = ANY({}attribute_ids) '.format(
prefix
)
format_dict['attribute_id'] = attribute_ids[0]
elif attributes and len(attribute_ids) == 0 and not use_range:
category_clause += ' AND FALSE '
return category_clause
def _format_date(date):
return datetime.datetime.strptime(date, '%Y-%m-%dT%H:%M:%S' + ('.%f' if '.' in date else '')).strftime(
DATE_FORMAT_STRING) if isinstance(date, str) else date.strftime(DATE_FORMAT_STRING)
def _format_tags(tags):
tags_arr = []
for tag in tags:
if tag['tag_id']:
tags_arr.append({
'tagId': tag['tag_id'],
'name': tag['tag_name']
})
return tags_arr
def _format_badges(badges):
badge_arr = []
for badge in badges:
if badge['name']:
badge_arr.append({
'name': badge['name'],
'level': badge['level'],
'value': badge['value'],
'timestamp': datetime.datetime.strptime(
badge['timestamp'].split('.')[0], DATE_FROM_STRING_SPLIT_FORMAT
).strftime(DATE_FORMAT_STRING) if badge['timestamp'] else None
})
return badge_arr
def _format_traits(traits):
traits_arr = []
for trait in traits:
if trait['attribute_name']:
trait_obj = {
'name': trait['attribute_name']
}
if trait['rarity_score']:
trait_obj['rarityScore'] = trait['rarity_score']
if trait['total_schema']:
trait_obj['totalSchema'] = trait['total_schema']
if trait['floor_price']:
trait_obj['floorPrice'] = trait['floor_price']
if trait['string_value']:
trait_obj['value'] = trait['string_value']
elif trait['int_value'] or trait['int_value'] == 0:
trait_obj['value'] = trait['int_value']
elif trait['float_value'] or trait['float_value'] == 0.0:
trait_obj['value'] = trait['float_value']
else:
trait_obj['value'] = trait['bool_value']
traits_arr.append(trait_obj)
return traits_arr
def _format_template(template):
try:
template_obj = {
'templateId': template['template_id'],
'name': template['name'],
'schema': template['schema'],
'collection': template['collection'],
'immutableData': json.loads(
template['template_immutable_data']) if template['template_immutable_data'] else '{}',
'createdAt': {
'date': _format_date(template['created_timestamp']),
'block': template['created_block_num'],
'globalSequence': template['created_seq'],
},
'maxSupply': template['max_supply'],
'traits': _format_traits(template['traits']) if template['traits'] else [],
}
if 'display_name' in template.keys():
template_obj['collection'] = {
'collectionName': template['collection'],
'displayName': template['display_name'],
'collectionImage': template['collection_image'],
'tags': _format_tags(template['tags']) if template['tags'] else [],
'badges': _format_badges(template['badges']) if template['badges'] else []
}
if 'rwax_symbol' in template.keys() and template['rwax_symbol']:
template_obj['rwax'] = {
'symbol': template['rwax_symbol'],
'contract': template['rwax_contract'],
'decimals': template['rwax_decimals'],
'tokenName': template['rwax_token_name'],
'tokenLogo': template['rwax_token_logo'],
'tokenLogoLarge': template['rwax_token_logo_lg'],
'templateMaxAssets': template['rwax_max_assets'],
'traitFactors': template['trait_factors'],
'rwaxTokenSupply': template['rwax_supply']
}
if template['video']:
template_obj['video'] = template['video']
if template['image']:
template_obj['image'] = template['image']
stats_obj = {}
if template['avg_wax_price'] and template['avg_usd_price']:
stats_obj['averageWaxPrice'] = template['avg_wax_price']
stats_obj['averageUsd'] = template['avg_usd_price']
if template['last_sold_wax'] and template['last_sold_usd']:
stats_obj['lastSoldWax'] = template['last_sold_wax']
stats_obj['lastSoldUsd'] = template['last_sold_usd']
if template['last_sold_timestamp'] and template['last_sold_listing_id'] and template[
'last_sold_wax'] and template['last_sold_usd']:
stats_obj['lastSold'] = {
'date': _format_date(template['last_sold_timestamp']),
'listingId': template['last_sold_listing_id'],
'priceWax': template['last_sold_wax'],
'priceUsd': template['last_sold_usd']
}
if template['volume_wax'] and template['volume_usd']:
stats_obj['volumeWax'] = template['volume_wax']
stats_obj['volumeUsd'] = template['volume_usd']
if template['num_sales']:
stats_obj['numSales'] = template['num_sales']
if template['num_burned']:
stats_obj['numBurned'] = template['num_burned']
if template['num_minted']:
stats_obj['numMinted'] = template['num_minted']
if template['floor_price']:
stats_obj['floorPrice'] = template['floor_price']
template_obj['stats'] = stats_obj
return template_obj
except Exception as e:
print(e)
return None
def _format_asset(asset):
try:
asset_obj = {
'assetId': asset['asset_id'],
'name': asset['name'],
'schema': asset['schema'],
'owner': asset['owner'],
'burned': asset['burned'],
'mint': asset['mint'],
'contract': asset['contract'],
'collection': asset['collection'],
'transferable': asset['transferable'],
'burnable': asset['burnable'],
'mutableData': json.loads(asset['mutable_data']) if asset['mutable_data'] else '{}',
'immutableData': json.loads(asset['immutable_data']) if asset['immutable_data'] else '{}',
'createdAt': {
'date': _format_date(asset['mint_timestamp']),
'block': asset['mint_block_num'],
'globalSequence': asset['mint_seq'],
},
'traits': _format_traits(asset['traits']) if asset['traits'] else [],
}
if 'display_name' in asset.keys():
asset_obj['collection'] = {
'collectionName': asset['collection'],
'displayName': asset['display_name'],
'collectionImage': asset['collection_image'],
'tags': _format_tags(asset['tags']) if 'tags' in asset.keys() and asset['tags'] else [],
'badges': _format_badges(asset['badges']) if 'badges' in asset.keys() and asset['badges'] else [],
'verification': asset['verified'],
'blacklisted': asset['blacklisted'] if 'blacklisted' in asset.keys() else None,
}
if asset['rarity_score']:
asset_obj['rarityScore'] = asset['rarity_score']
asset_obj['rank'] = asset['rank']
asset_obj['numTraits'] = asset['num_traits']
if 'rwax_symbol' in asset.keys() and asset['rwax_symbol']:
asset_obj['rwax'] = {
'symbol': asset['rwax_symbol'],
'contract': asset['rwax_contract'],
'decimals': asset['rwax_decimals'],
'tokenName': asset['rwax_token_name'],
'tokenLogo': asset['rwax_token_logo'],
'tokenLogoLarge': asset['rwax_token_logo_lg'],
'templateMaxAssets': asset['rwax_max_assets'],
'redeemAmount': asset['rwax_amount'],
'traitFactors': _format_object(asset['trait_factors']),
'rwaxTokenSupply': asset['rwax_supply']
}
if asset['video']:
asset_obj['video'] = asset['video']
if asset['image']:
asset_obj['image'] = asset['image']
if 'template_id' in asset.keys() and asset['template_id']:
stats_obj = {}
if asset['avg_wax_price'] and asset['avg_usd_price']:
stats_obj['averageWaxPrice'] = asset['avg_wax_price']
stats_obj['averageUsd'] = asset['avg_usd_price']
if asset['last_sold_wax'] and asset['last_sold_usd']:
stats_obj['lastSoldWax'] = asset['last_sold_wax']
stats_obj['lastSoldUsd'] = asset['last_sold_usd']
if asset['last_sold_timestamp'] and asset['last_sold_listing_id'] and asset['last_sold_wax'] and asset[
'last_sold_usd']:
stats_obj['lastSold'] = {
'date': _format_date(asset['last_sold_timestamp']),
'listingId': asset['last_sold_listing_id'],
'priceWax': asset['last_sold_wax'],
'priceUsd': asset['last_sold_usd']
}
if asset['volume_wax'] and asset['volume_usd']:
stats_obj['volumeWax'] = asset['volume_wax']
stats_obj['volumeUsd'] = asset['volume_usd']
if asset['num_sales']:
stats_obj['numSales'] = asset['num_sales']
if asset['num_burned']:
stats_obj['numBurned'] = asset['num_burned']
if asset['num_minted']:
stats_obj['numMinted'] = asset['num_minted']
if asset['floor_price']:
stats_obj['floorPrice'] = asset['floor_price']
asset_obj['template'] = {
'templateId': asset['template_id'],
'immutableData': json.loads(asset['template_immutable_data']) if asset[
'template_immutable_data'] else '{}',
'stats': stats_obj,
}
if 'listings' in asset.keys():
asset_obj['listings'] = _format_object(asset['listings'])
return asset_obj
except Exception as e:
print(e)
return None
def _format_schema(schema):
asset_obj = {
'schema': schema['schema'],
'stats': {
'numTemplates': schema['num_templates'],
'numAssets': schema['num_minted'],
'numBurned': schema['num_burned'],
'volumeWAX': schema['volume_wax'],
'volumeUSD': schema['volume_usd'],
},
'collection': {
'collectionName': schema['collection'],
'displayName': schema['display_name'],
'collectionImage': schema['collection_image'],
'tags': _format_tags(schema['tags']) if schema['tags'] else [],
'badges': _format_badges(schema['badges']) if schema['badges'] else [],
'verification': schema['verified']
},
'createdAt': {
'date': schema['created_timestamp'].strftime(DATE_FORMAT_STRING),
'block': schema['created_block_num'],
'globalSequence': schema['created_seq'],
}
}
return asset_obj
def _format_assets_object(items):
assets = []
for item in items:
asset = _format_asset(item)
if asset:
assets.append(asset)
return assets
def _format_listings(item):
return {
'date': item['timestamp'].strftime(DATE_FORMAT_STRING),
'timestamp': datetime.datetime.timestamp(item['timestamp']), 'price': item['price'],
'usdWax': item['usd_wax'], 'currency': item['currency'], 'market': item['market'],
'maker': item['maker'], 'seller': item['seller'], 'listingId': item['listing_id'],
'uniqueSaleId': item['sale_id'],
'collection': {
'collectionName': item['collection'],
'displayName': item['display_name'],
'collectionImage': item['collection_image'],
'verification': item['verified'],
'blacklisted': item['blacklisted']
},
'assets': _format_assets_object(item['assets'])
}
def _get_search_term(session, term):
template_id = None
asset_id = None
name = None
collection = None
if (isinstance(term, int) or (isinstance(term, str) and term.isnumeric())) and int(term) < 1099511627776:
template = session.execute(
'SELECT template_id, collection FROM templates WHERE template_id = :term', {
'term': term
}
).first()
if template:
template_id = template['template_id']
collection = template['collection']
elif (isinstance(term, int) or (isinstance(term, str) and term.isnumeric())) and int(term) >= 1099511627776:
asset = session.execute(
'SELECT asset_id, collection FROM assets WHERE asset_id = :term', {
'term': term
}
).first()
if asset:
asset_id = asset['asset_id']
collection = asset['collection']
else:
name = term
return name, asset_id, template_id, collection
def _get_mint_filter(min_mint, max_mint, format_dict):
search_clause = ''
if min_mint and max_mint:
search_clause += (
'AND a.mint BETWEEN :min_mint AND :max_mint '
)
format_dict['min_mint'] = min_mint
format_dict['max_mint'] = max_mint
elif min_mint:
search_clause += (
'AND a.mint >= :min_mint '
)
format_dict['min_mint'] = min_mint
elif max_mint:
search_clause += (
'AND a.mint <= :max_mint '
)
format_dict['max_mint'] = max_mint
return search_clause
def _get_recently_sold_join_filter(recently_sold):
filter_join_clause = ''
if recently_sold:
table = 'recently_sold_month_mv'
if recently_sold == 'hour':
table = 'recently_sold_hour_mv'
elif recently_sold == 'day':
table = 'recently_sold_day_mv'
elif recently_sold == 'week':
table = 'recently_sold_week_mv'
filter_join_clause += (
'INNER JOIN {table} USING (template_id) '.format(table=table)
)
return filter_join_clause
def _get_recently_sold_filter(recently_sold):
search_clause = ''
if recently_sold:
table = 'recently_sold_month_mv'
if recently_sold == 'hour':
table = 'recently_sold_hour_mv'
elif recently_sold == 'day':
table = 'recently_sold_day_mv'
elif recently_sold == 'week':
table = 'recently_sold_week_mv'
search_clause += (
' AND a.template_id IN ('
' SELECT template_id FROM {table} WHERE template_id = a.template_id'
') '.format(table=table)
)
return search_clause
def parallel(requests):
"""Execute requests in parallel.
Provided a dict of requests, execute them with the provided id and kwargs.
Return the results of these requests in a dict keyed by keys in the
requests parameter.
"""
futures = {
executor.submit(
request['func'],
*request['args']
): key for (key, request) in requests.items()
}
concurrent.futures.wait(futures)
output = dict(map(lambda f: (futures[f], f.result()), futures))
# Format the responses for errors, return as oto response
return output
def newest_listings(collection, schema, template_id):
global last_reported_order
try:
sales_results = listings(
term=template_id, schema=schema, collection=collection,
order_by='date_desc', limit=24, search_type='sales'
)
sales = []
max_order = 0
has_new_element = False
for sale in sales_results:
new_sale = {}
for key in sale.keys():
if key != 'displayData':
if sale[key]:
new_sale[key] = sale[key].replace('\'', '') if isinstance(sale[key], str) else sale[key]
if new_sale['verified']:
new_sale['verified'] = 1
new_sale.pop('mdata', None)
sales.append(new_sale)
if new_sale['orderId'] > max_order:
max_order = new_sale['orderId']
if template_id not in last_reported_order.keys():
last_reported_order[template_id] = 0
if max_order > last_reported_order[template_id]:
last_reported_order[template_id] = max_order
has_new_element = True
return {'hasNewElement': 1 if has_new_element else 0, 'elements': sales}
except Exception as e:
print(e)
return {'hasNewElement': 0, 'elements': []}
def _parse_order(order_by):
order_dir = 'ASC'
if '_asc' in order_by:
order_dir = 'ASC'
order_by = order_by.replace('_asc', '')
elif '_desc' in order_by:
order_dir = 'DESC'
order_by = order_by.replace('_desc', '')
return order_dir, order_by
def schemas(
term=None, collection=None, schema=None, limit=100, order_by='name_asc', exact_search=False, offset=0
):
session = create_session()
order_dir, order_by = _parse_order(order_by)
try:
format_dict = {'limit': limit, 'offset': offset}
limit_clause = 'LIMIT :limit OFFSET :offset'
search_clause = ''
order_clause = ''
personal_blacklist_clause = ''
search_category_clause = ''
if collection:
format_dict['collection'] = collection
search_category_clause += ' AND a.collection = :collection '
if schema:
format_dict['schema'] = schema
search_category_clause += ' AND a.schema = :schema '
search_clause += search_category_clause
if term:
if exact_search:
search_clause += (
' AND a.schema = :search_name '
)
format_dict['search_name'] = '{}'.format(term)
else:
search_clause += (
' AND a.schema LIKE :search_name '
)
format_dict['search_name'] = '%{}%'.format(term)
source_clause = (
'schemas a '
)
columns_clause = (
'a.schema, cn.name AS display_name, a.collection, col.verified, schema_format, {badges_object}, {tags_obj}, '
'ci.image as collection_image, a.timestamp AS created_timestamp, a.block_num AS created_block_num, '
'a.seq AS created_seq, ts.num_minted, ts.num_templates, ts.num_burned, ts.volume_wax, '
'ts.volume_usd, (SELECT MIN(floor_price) '
' FROM templates t '
' INNER JOIN floor_prices_mv USING(template_id) '
' WHERE t.collection = a.collection AND t.schema = a.schema'
') AS floor_price'.format(
badges_object=_get_badges_object(), tags_obj=_get_tags_object()
)
)
if order_by == 'date':
order_clause = 'ORDER BY a.seq {}'.format(order_dir)
elif order_by == 'num_templates':
order_clause = 'ORDER BY num_templates ' + order_dir
elif order_by == 'num_assets':
order_clause = 'ORDER BY COALESCE(num_minted, 0) - COALESCE(num_burned, 0) ' + order_dir
elif order_by == 'volume':
order_clause = 'ORDER BY volume_wax ' + order_dir
sql = (
' SELECT {columns_clause} '
' FROM {source_clause} '
' LEFT JOIN collections col USING (collection) '
' LEFT JOIN schema_stats_mv ts USING (collection, schema) '
' LEFT JOIN names cn ON (col.name_id = cn.name_id) '
' LEFT JOIN images ci ON (col.image_id = ci.image_id) '
' WHERE TRUE {search_clause} '
' {personal_blacklist_clause} '
' {order_clause} {limit_clause}'.format(
columns_clause=columns_clause,
source_clause=source_clause,
search_clause=search_clause,
order_clause=order_clause,
limit_clause=limit_clause,
personal_blacklist_clause=personal_blacklist_clause
))
res = session.execute(sql, format_dict)
results = []
for row in res:
try:
result = _format_schema(row)
results.append(result)
except Exception as e:
logging.error(e)
return results
except SQLAlchemyError as e:
logging.error(e)
session.rollback()
raise e
finally:
session.remove()
def get_health():
session = create_session()
try:
result = session.execute(
'SELECT block_num, timestamp '
'FROM chronicle_transactions '
'WHERE seq = (SELECT MAX(seq) FROM chronicle_transactions)'
).first()
if result:
return {
'success': 'true',
'block_num': result['block_num'],
'timestamp': result['timestamp'].strftime("%Y-%m-%d %H:%M:%S")
}
return {
'success': 'false'
}
except SQLAlchemyError as e:
logging.error(e)
session.rollback()
raise e
finally:
session.remove()
def filter_attributes(collection, schema=None, templates=None, only=None):
session = create_session()
search_dict = {
'collection': collection
}
schema_clause = ''
if schema:
schema_clause += ' AND a.schema = :schema'
search_dict['schema'] = schema
if templates:
schema_clause += ' AND t.template_id IN :templates '
search_dict['templates'] = tuple(templates.split(','))
join_clause = ''
if only == 'rwax':
join_clause = 'INNER JOIN rwax_tokens USING(collection, schema) '
sql = (
'SELECT attribute_name, string_value, bool_value, MIN(int_value) AS min_int_value, '
'MAX(int_value) AS max_int_value, MIN(float_value) AS min_float_value, MAX(float_value) AS max_float_value,'
'SUM(int_value * max_supply) / (CASE WHEN SUM(max_supply) = 0 THEN 1 ELSE SUM(max_supply) END) '
'AS avg_int_value, SUM(float_value * max_supply) / (CASE WHEN SUM(max_supply) = 0 THEN 1 ELSE '
'SUM(max_supply) END) AS avg_float_value, SUM(max_supply) AS max_supply, SUM(num_minted) AS num_minted '
'FROM attributes a '
'{join_clause} '
'LEFT JOIN template_attributes_mapping ta ON a.collection = ta.collection AND a.schema = ta.schema '
'AND a.attribute_id = ta.attribute_id '
'LEFT JOIN templates t ON a.collection = t.collection AND a.schema = t.schema '
'AND t.template_id = ta.template_id '
'LEFT JOIN templates_minted_mv tm ON tm.template_id = t.template_id '
'WHERE a.collection = :collection '
'{schema_clause} '
'GROUP BY 1, 2, 3 '
'ORDER BY attribute_name ASC, string_value ASC'.format(
schema_clause=schema_clause, join_clause=join_clause
)
)
res = session.execute(
sql,
search_dict
)
attributes = {}
for attribute in res:
value = attribute['string_value']
attribute_type = None
min_value = 0
max_value = 0
avg_value = 0
if value:
attribute_type = 'string'
else:
min_value = attribute['min_int_value']
max_value = attribute['max_int_value']
avg_value = attribute['avg_int_value']
if min_value or max_value or max_value == 0:
attribute_type = 'integer'
else:
min_value = attribute['min_float_value']
max_value = attribute['max_float_value']
avg_value = attribute['avg_float_value']
if min_value or max_value or max_value == 0.0:
attribute_type = 'float'
if not attribute_type:
value = attribute['bool_value']
attribute_type = 'boolean'
if value and attribute_type in ['string', 'boolean']:
num_minted = attribute['num_minted']
max_supply = attribute['max_supply']
if attribute['attribute_name'] in attributes.keys():
attributes[attribute['attribute_name']]['values'].append(
{
'value': value,
'maxSupply': int(max_supply) if max_supply else 0,
'numMinted': int(num_minted) if num_minted else 0
}
)
else:
attributes[attribute['attribute_name']] = {
'values': [{
'value': value,
'maxSupply': int(max_supply) if max_supply else 0,
'numMinted': int(num_minted) if num_minted else 0
}],
'type': attribute_type
}
elif attribute_type in ['float', 'integer']:
attributes[attribute['attribute_name']] = {
'minValue': float(min_value) if min_value else 0,
'maxValue': float(max_value) if max_value else 0,
'avgValue': float(avg_value) if avg_value else 0,
'type': attribute_type
}
return attributes
def collection_filters(collection):
session = create_session()
search_dict = {
'collection': collection
}
res = session.execute(
'SELECT attribute_name, string_value, MIN(int_value) AS min_int_value, MAX(int_value) AS max_int_value, '
'MIN(float_value) AS min_float_value, MAX(float_value) AS max_float_value, bool_value '
'FROM attributes a '
'WHERE collection = :collection '
'GROUP BY 1, 2, 7 '
'ORDER BY attribute_name ASC, string_value ASC',
search_dict
)
attributes = {}