-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstats_v3.py
1918 lines (1697 loc) · 75.5 KB
/
stats_v3.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 json
import time
from sqlalchemy.exc import SQLAlchemyError
from api import cache, logging, db
import datetime
def create_session():
return db.session
def _format_assets(assets):
asset_list = []
for asset in assets:
asset_list.append({
'assetId': asset['asset_id'],
'name': asset['name'],
'mint': asset['mint'],
'image': asset['image'],
'templateId': asset['template_id']
})
return asset_list
def _create_date_list(days):
dates = range(days)
items = []
for date in dates:
d = datetime.datetime.today() - datetime.timedelta(days=(days - (date + 1)))
items.append(d.strftime("%Y-%m-%d"))
return items
def _create_empty_chart(key, days, key2=None, key3=None):
dates = range(days)
items = []
for date in dates:
d = datetime.datetime.today() - datetime.timedelta(days=(days - (date + 1)))
if key3:
items.append({
key: 0,
key2: 0,
key3: 0,
'date': d.strftime("%Y-%m-%d")
})
elif key2:
items.append({
key: 0,
key2: 0,
'date': d.strftime("%Y-%m-%d")
})
else:
items.append({
key: 0,
'date': d.strftime("%Y-%m-%d")
})
return items
def add_trend(res):
dates = _create_empty_chart('waxVolume', 7)
dates[0]['waxVolume'] = res['wax_volume_day_1'] if 'wax_volume_day_1' in res.keys() else 0
dates[1]['waxVolume'] = res['wax_volume_day_2'] if 'wax_volume_day_2' in res.keys() else 0
dates[2]['waxVolume'] = res['wax_volume_day_3'] if 'wax_volume_day_3' in res.keys() else 0
dates[3]['waxVolume'] = res['wax_volume_day_4'] if 'wax_volume_day_4' in res.keys() else 0
dates[4]['waxVolume'] = res['wax_volume_day_5'] if 'wax_volume_day_5' in res.keys() else 0
dates[5]['waxVolume'] = res['wax_volume_day_6'] if 'wax_volume_day_6' in res.keys() else 0
dates[6]['waxVolume'] = res['wax_volume_day_7'] if 'wax_volume_day_7' in res.keys() else 0
return dates
@cache.memoize(timeout=300)
def user_stats(user):
session = create_session()
try:
res = session.execute(
'SELECT owner as user_name, wax_value, usd_value, num_assets, image, '
'SUM(s.wax_volume_all_time + b.wax_volume_all_time) AS wax_volume_all_time, '
'SUM(s.usd_volume_all_time + b.usd_volume_all_time) AS usd_volume_all_time, '
'SUM(s.wax_volume_all_time) AS wax_sell_volume_all_time, '
'SUM(s.usd_volume_all_time) AS usd_sell_volume_all_time, '
'SUM(b.wax_volume_all_time) AS wax_buy_volume_all_time, '
'SUM(b.usd_volume_all_time) AS usd_buy_volume_all_time, '
'SUM(b.purchases_all_time) AS purchases_all_time, '
'SUM(s.purchases_all_time) AS sales_all_time '
'FROM users_mv '
'LEFT JOIN seller_volumes_mv s ON owner = s.user_name '
'LEFT JOIN buyer_volumes_mv b ON owner = b.user_name '
'LEFT JOIN user_pictures_mv up ON owner = up.user_name '
'WHERE owner = :owner GROUP BY 1, 2, 3, 4, 5 ',
{'owner': user}
).first()
if not res:
return {
'numUsers': 'Error',
'waxValue': 'Error',
'usdValue': 'Error',
'numAssets': 'Error'
}
return {
'name': res.user_name,
'image': res.image,
'waxValue': float(res.wax_value if res.wax_value else 0),
'usdValue': float(res.usd_value if res.usd_value else 0),
'numAssets': int(res.num_assets if res.num_assets else 0),
'waxVolumeAllTime': float(res.wax_volume_all_time if res.wax_volume_all_time else 0),
'usdVolumeAllTime': float(res.usd_volume_all_time if res.usd_volume_all_time else 0),
'waxBuyVolumeAllTime': float(res.wax_buy_volume_all_time if res.wax_buy_volume_all_time else 0),
'usdBuyVolumeAllTime': float(res.usd_buy_volume_all_time if res.usd_buy_volume_all_time else 0),
'waxSellVolumeAllTime': float(res.wax_sell_volume_all_time if res.wax_sell_volume_all_time else 0),
'usdSellVolumeAllTime': float(res.usd_sell_volume_all_time if res.usd_sell_volume_all_time else 0),
'purchasesAllTime': float(res.purchases_all_time if res.purchases_all_time else 0),
'salesAllTime': float(res.sales_all_time if res.sales_all_time else 0),
}
except SQLAlchemyError as e:
logging.error(e)
session.rollback()
raise e
finally:
session.remove()
@cache.memoize(timeout=300)
def collection_stats(collection):
session = create_session()
try:
res = session.execute(
'SELECT num_users, wax_value, usd_value, num_assets '
'FROM collection_user_count_mv '
'WHERE collection = :collection',
{'collection': collection}
).first()
if not res:
return {
'numUsers': 0,
'usdMarketCap': 0,
'waxMarketCap': 0,
'numAssets': 0,
}
return {
'numUsers': res.num_users,
'usdMarketCap': float(res.usd_value if res.usd_value else 0),
'waxMarketCap': float(res.wax_value if res.wax_value else 0),
'numAssets': int(res.num_assets if res.num_assets else 0),
}
except SQLAlchemyError as e:
logging.error(e)
session.rollback()
raise e
finally:
session.remove()
@cache.memoize(timeout=300)
def get_user_info(user):
session = create_session()
try:
res = session.execute(
'SELECT owner as user_name, wax_value, usd_value, num_assets, image '
'FROM users_mv '
'LEFT JOIN user_pictures_mv up ON owner = user_name '
'WHERE owner = :owner ',
{'owner': user}
).first()
if not res:
return {
'name': 'Error',
'image': 'Error',
'waxValue': 'Error',
'usdValue': 'Error',
'numAssets': 'Error'
}
return {
'name': res.user_name,
'image': res.image,
'waxValue': float(res.wax_value if res.wax_value else 0),
'usdValue': float(res.usd_value if res.usd_value else 0),
'numAssets': int(res.num_assets if res.num_assets else 0)
}
except SQLAlchemyError as e:
logging.error(e)
session.rollback()
raise e
finally:
session.remove()
@cache.memoize(timeout=300)
def get_monthly_volume(collection, days, type):
session = create_session()
try:
res = session.execute(
'SELECT to_date, SUM(wax_volume) AS wax_volume, SUM(usd_volume) AS usd_volume '
'FROM monthly_collection_volume_mv WHERE TRUE {type_clause} {date_clause} {collection_clause} '
'GROUP BY 1 ORDER BY 1 ASC'.format(
collection_clause=' AND collection = :collection ' if collection and collection != '*' else '',
type_clause=' AND type = :type ' if type and type != 'all' else '',
date_clause=' AND to_date >= NOW() AT TIME ZONE \'utc\' - INTERVAL :interval' if days and int(
days) > 0 else '',
), {'type': type, 'collection': collection, 'interval': '{} days'.format(days)},
)
volumes = []
for item in res:
volumes.append({
'date': item['to_date'].strftime("%Y-%m-%d"),
'waxVolume': item['wax_volume'],
'usdVolume': item['usd_volume']
})
return volumes
except SQLAlchemyError as e:
logging.error(e)
session.rollback()
raise e
finally:
session.remove()
@cache.memoize(timeout=300)
def get_users_table(days, collection, actor, type, term):
session = create_session()
try:
table = 'volume_'
if collection:
table += 'collection_'
if actor == 'buyer':
table += 'buyer_'
else:
table += 'seller_'
if days and days != '0':
table += days + '_days_mv'
else:
table += 'all_time_mv'
search_clause = ''
if term:
search_clause = ' HAVING user_name ilike :term '
users = []
if actor == 'all':
total_result = session.execute(
'SELECT MAX(actors) AS total_results '
'FROM ('
'SELECT COUNT(DISTINCT seller) AS actors '
'FROM {seller_table} '
'WHERE TRUE {collection_clause} {type_clause} '
'UNION ALL '
'SELECT COUNT(DISTINCT buyer) AS actors '
'FROM {buyer_table} '
'WHERE TRUE {collection_clause} {type_clause}) f'
' '.format(
seller_table=table,
buyer_table=table.replace('_seller_', '_buyer_'),
collection_clause=' AND tb.collection = :collection ' if collection and collection != '*' else '',
type_clause=' AND type = :type ' if type and type != 'all' else ''
), {
'actor': actor, 'type': type, 'collection': collection
}
).first()
sql = (
'SELECT * FROM (SELECT '
'SUM(wax_volume) AS wax_volume, '
'SUM(usd_volume) AS usd_volume, '
'SUM(CASE WHEN actor = \'buyer\' THEN wax_volume ELSE 0 END) AS wax_buy_volume, '
'SUM(CASE WHEN actor = \'buyer\' THEN usd_volume ELSE 0 END) AS usd_buy_volume, '
'SUM(CASE WHEN actor = \'seller\' AND type = \'sales\' THEN wax_volume ELSE 0 END) AS wax_sell_volume, '
'SUM(CASE WHEN actor = \'seller\' AND type = \'sales\' THEN usd_volume ELSE 0 END) AS usd_sell_volume, '
'SUM(CASE WHEN actor = \'buyer\' THEN sales ELSE 0 END) AS purchases, '
'SUM(CASE WHEN actor = \'seller\' AND type = \'sales\' THEN sales ELSE 0 END) AS sales, '
'user_name, image, ROW_NUMBER() OVER ('
'ORDER BY SUM(CASE WHEN actor = \'seller\' AND type != \'sales\' THEN 0 ELSE usd_volume END) DESC'
') AS rank '
'FROM ('
' SELECT seller AS user_name, '
' \'seller\' AS actor, type, '
' SUM(wax_volume) AS wax_volume, '
' SUM(usd_volume) AS usd_volume, '
' SUM(sales) AS sales'
' FROM {seller_table} '
' WHERE TRUE {collection_clause} {type_clause} AND type = \'sales\''
' GROUP BY 1, 2, 3 '
'UNION ALL '
' SELECT buyer AS user_name, '
' \'buyer\' AS actor, type, '
' SUM(wax_volume) AS wax_volume, '
' SUM(usd_volume) AS usd_volume, '
' SUM(sales) AS sales'
' FROM {buyer_table} '
' WHERE TRUE {collection_clause} {type_clause} '
' GROUP BY 1, 2, 3 '
') tb LEFT JOIN user_pictures_mv up USING (user_name) '
'GROUP BY user_name, image) f '
'GROUP BY 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 {search_clause} '
'ORDER BY 2 DESC '.format(
seller_table=table,
buyer_table=table.replace('_seller_', '_buyer_'),
collection_clause=' AND tb.collection = :collection ' if collection and collection != '*' else '',
type_clause=' AND type = :type ' if type and type != 'all' else '',
search_clause=search_clause,
)
)
user_results = session.execute(
sql, {
'interval': '{} days'.format(days), 'collection': collection, 'term': term, 'actor': actor,
'type': type
}
)
for user in user_results:
users.append(
{
'userName': user.user_name,
'image': user.image,
'total': total_result['total_results'],
'stats': {
'days': days,
'waxVolume': float(user.wax_volume if user.wax_volume else 0),
'usdVolume': float(user.usd_volume if user.usd_volume else 0),
'waxBuyVolume': float(user.wax_buy_volume if user.wax_buy_volume else 0),
'usdBuyVolume': float(user.usd_buy_volume if user.usd_buy_volume else 0),
'waxSellVolume': float(user.wax_sell_volume if user.wax_sell_volume else 0),
'usdSellVolume': float(user.usd_sell_volume if user.usd_sell_volume else 0),
'purchases': float(user.purchases if user.purchases else 0),
'sales': float(user.sales if user.sales else 0),
'rank': int(user.rank)
}
}
)
else:
total_result = session.execute(
'SELECT COUNT(1) AS total_results '
'FROM {table} tb '
'WHERE TRUE {collection_clause} {type_clause} '.format(
table=table,
collection_clause=' AND tb.collection = :collection ' if collection and collection != '*' else '',
type_clause=' AND type = :type ' if type and type != 'all' else ''
), {
'actor': actor, 'type': type, 'collection': collection
}
).first()
sql = (
'SELECT {actor} AS user_name, image, '
'SUM(wax_volume) AS wax_volume, '
'SUM(usd_volume) AS usd_volume, '
'SUM(sales) AS sales, '
'ROW_NUMBER() OVER ('
' ORDER BY SUM(usd_volume) DESC'
') AS rank '
'FROM {table} tb LEFT JOIN user_pictures_mv up ON ({actor} = user_name) '
'WHERE TRUE {collection_clause} {type_clause} {sales_clause} GROUP BY 1, 2 {search_clause} '
'ORDER BY 4 DESC '.format(
table=table, actor=actor,
collection_clause=' AND tb.collection = :collection ' if collection and collection != '*' else '',
type_clause=' AND type = :type ' if type and type != 'all' else '',
sales_clause=' AND type = \'sales\'' if actor == 'seller' else '',
search_clause=search_clause,
)
)
user_results = session.execute(
sql, {
'interval': '{} days'.format(days), 'collection': collection, 'term': term, 'actor': actor,
'type': type
}
)
for user in user_results:
users.append(
{
'userName': user.user_name,
'image': user.image,
'total': total_result['total_results'],
'stats': {
'days': days,
'waxVolume': float(user.wax_volume if user.wax_volume else 0),
'usdVolume': float(user.usd_volume if user.usd_volume else 0),
'sales': float(user.sales if user.sales else 0),
'rank': int(user.rank)
}
}
)
return users
except SQLAlchemyError as e:
logging.error(e)
session.rollback()
finally:
session.remove()
@cache.memoize(timeout=300)
def get_sales_volume_graph(days=60, template_id=None, collection=None, type='all'):
session = create_session()
try:
sales_volume = session.execute(
'SELECT date, SUM(price) AS volume, SUM(usd_price) AS usdVolume, SUM(sales) AS sales '
'FROM {template}sales_by_date t '
'WHERE TRUE {date_clause}{collection_clause}{type_clause}{template_clause}'
'GROUP BY 1 ORDER BY 1 DESC'.format(
template='template_' if template_id else '',
date_clause=' AND date >= NOW() AT TIME ZONE \'utc\' - INTERVAL :interval ' if days and int(days) > 0 else '',
type_clause=' AND type = :type ' if type and type != 'all' else '',
template_clause=' AND template_id = :template_id ' if template_id else '',
collection_clause=' AND collection = :collection ' if collection else ''
), {
'interval': '{} days'.format(days),
'collection': collection,
'template_id': template_id,
'type': type
}
)
dates = _create_empty_chart('waxVolume', int(days), 'usdVolume', 'sales')
for item in sales_volume:
date = item['date'].strftime("%Y-%m-%d")
for date_item in dates:
if date_item['date'] == date:
date_item['waxVolume'] = float(item['waxVolume'])
date_item['usdVolume'] = float(item['usd_volume'])
date_item['sales'] = int(item['sales'])
return dates
except SQLAlchemyError as e:
logging.error(e)
session.rollback()
raise e
except Exception as e:
logging.error(e)
raise e
finally:
session.remove()
@cache.memoize(timeout=300)
def get_sales_volume_graph(days=60, template_id=None, collection=None, type='all'):
session = create_session()
try:
sql = (
'SELECT to_date, SUM(wax_volume) AS wax_volume, SUM(usd_volume) AS usd_volume, SUM(sales) AS sales '
'FROM {template}collection_sales_by_date_mv t '
'WHERE TRUE {date_clause}{collection_clause}{type_clause}{template_clause}'
'GROUP BY 1 ORDER BY 1 DESC'.format(
template='template_' if template_id else '',
date_clause=' AND to_date >= NOW() AT TIME ZONE \'utc\' - INTERVAL :interval ' if days and int(
days) > 0 else '',
type_clause=' AND t.type = :type ' if type and type != 'all' else '',
template_clause=' AND template_id = :template_id ' if template_id else '',
collection_clause=' AND collection = :collection ' if collection and collection != '*' else ''
)
)
sales_volume = session.execute(
sql, {
'interval': '{} days'.format(days),
'collection': collection,
'template_id': template_id,
'type': type
}
)
dates = _create_empty_chart('waxVolume', int(days), 'sales', 'usdVolume')
for item in sales_volume:
date = item['to_date'].strftime("%Y-%m-%d")
for date_item in dates:
if date_item['date'] == date:
date_item['waxVolume'] = float(item['wax_volume'])
date_item['usdVolume'] = float(item['usd_volume'])
date_item['sales'] = int(item['sales'])
return dates
except SQLAlchemyError as e:
logging.error(e)
session.rollback()
raise e
except Exception as e:
logging.error(e)
raise e
finally:
session.remove()
@cache.memoize(timeout=300)
def get_drops_table(days, limit, offset):
session = create_session()
try:
table = 'volume_drop_all_time_mv'
if days and days != '0':
table = 'volume_drop_{days}_days_mv'.format(days=days)
total_result = session.execute(
'SELECT COUNT(1) AS total_results '
'FROM {table} tb '.format(
table=table
)
).first()
drops_result = session.execute(
'SELECT dv.drop_id, dv.market, d.display_data, d.collection, cn.name AS display_name, '
'ci.image AS collection_image, wax_volume, usd_volume, buyers, sales AS claims, '
'json_agg(json_build_object(\'template_id\', t.template_id, \'data\', td.data)) AS template_data, '
'COUNT(1) AS total_amount, ROW_NUMBER() OVER (ORDER BY wax_volume DESC) AS rank '
'FROM {table} dv '
'LEFT JOIN drops d ON d.drop_id = dv.drop_id AND d.contract = dv.market '
'LEFT JOIN templates t ON t.template_id = ANY(templates_to_mint) '
'LEFT JOIN data td ON t.immutable_data_id = td.data_id '
'LEFT JOIN collections c ON c.collection = d.collection '
'LEFT JOIN images ci ON c.image_id = ci.image_id '
'LEFT JOIN names cn ON c.name_id = cn.name_id '
'GROUP BY 1,2,3,4,5,6,7,8,9,10 ORDER BY wax_volume DESC '
'LIMIT :limit OFFSET :offset'.format(
table=table
), {'limit': limit, 'offset': offset}
)
drops = []
for drop in drops_result:
templates_data = drop['template_data']
templates = []
for template_data in templates_data:
template = {}
template['templateId'] = template_data['template_id']
template['data'] = json.loads(template_data['data'])
templates.append(template)
try:
drop_data = json.loads(drop['display_data'])
except Exception as err:
drop_data = {}
print(err)
if isinstance(drop_data, str):
display_data = drop_data
drop_data = {'displayData': display_data}
drop_data['dropId'] = drop['drop_id']
drop_data['market'] = drop['market']
drops.append(
{
'templates': templates,
'drop': drop_data,
'total': total_result['total_results'],
'collection': {
'name': drop.collection,
'displayName': drop.display_name,
'image': drop.collection_image,
},
'stats': {
'days': days,
'waxVolume': float(drop.wax_volume if drop.wax_volume else 0),
'usdVolume': float(drop.usd_volume if drop.usd_volume else 0),
'buyers': int(drop.buyers),
'claims': int(drop.claims),
'rank': int(drop.rank)
}
}
)
return drops
except SQLAlchemyError as e:
logging.error(e)
session.rollback()
finally:
session.remove()
def _parse_data_object(data):
result = {}
for item in data:
result[item['key']] = item['value'][1]
return result
@cache.memoize(timeout=300)
def get_template_table(days, collection, limit, offset):
session = create_session()
try:
table = 'volume_template_all_time_mv'
if days and days != '0' and int(days) == 1:
table = 'volume_template_{days}_days_mv'.format(days=days)
total_result = session.execute(
'SELECT COUNT(1) AS total_results '
'FROM {table} tb '
'WHERE TRUE {collection_clause} AND tb.collection NOT IN ('
'SELECT collection FROM collections ba WHERE blacklisted) '.format(
table=table,
collection_clause=' AND tb.collection = :collection ' if collection and collection != '*' else ''
), {
'collection': collection
}
).first()
template_results = session.execute(
'SELECT wax_volume, usd_volume, '
'(SELECT wax_volume FROM volume_template_1_days_mv WHERE template_id = t.template_id) AS volume_1_day, '
'(SELECT wax_volume FROM volume_template_2_days_mv WHERE template_id = t.template_id) AS volume_2_days, '
'buyers, sellers, sales, '
'tb.collection, cn.name, ci.image, t.template_id, t.schema, td.data AS idata, '
'(SELECT floor_price FROM template_floor_prices_mv WHERE template_id = t.template_id) as floor_price, '
'ROW_NUMBER() OVER (ORDER BY 1 DESC) AS rank '
'FROM {table} tb '
'INNER JOIN collections c USING (collection) '
'INNER JOIN templates t USING(template_id) '
'LEFT JOIN images ci ON c.image_id = ci.image_id '
'LEFT JOIN names cn ON c.name_id = cn.name_id '
'LEFT JOIN data td ON td.data_id = t.immutable_data_id '
'WHERE TRUE {collection_clause} AND NOT blacklisted '
'ORDER BY 1 DESC '
'LIMIT :limit OFFSET :offset '.format(
table=table,
collection_clause=' AND tb.collection = :collection ' if collection and collection != '*' else '',
), {
'collection': collection,
'limit': limit,
'offset': offset
}
)
collections = []
for template in template_results:
template_data = _parse_data_object(json.loads(template['idata']))
template_data['template_id'] = template['template_id']
template_data['schema'] = template['schema']
collections.append(
{
'template': template_data,
'total': total_result['total_results'],
'collection': {
'name': template.collection,
'displayName': template.name,
'image': template.image,
},
'stats': {
'days': days,
'waxVolume': float(template.wax_volume if template.wax_volume else 0),
'usdVolume': float(template.usd_volume if template.usd_volume else 0),
'waxFloor': float(template.floor_price if template.floor_price else 0),
'change': float(
((template.volume_1_day - (template.volume_2_days - template.volume_1_day)) / (
template.volume_2_days - template.volume_1_day))
if template.volume_1_day and template.volume_2_days - template.volume_1_day else 0),
'buyers': int(template.buyers),
'sellers': int(template.sellers),
'sales': int(template.sales),
'rank': int(template.rank)
}
}
)
return collections
except SQLAlchemyError as e:
logging.error(e)
session.rollback()
finally:
session.remove()
@cache.memoize(timeout=300)
def get_top_sales_table(days, collection, template_id, limit, offset):
session = create_session()
try:
res = session.execute(
'SELECT wax_price, usd_price, buyer, seller, ct.transaction_id AS buy_transaction_id, t.collection, '
'cn.name, ci.image as collection_image, CASE WHEN taker IS NULL THEN market ELSE taker END AS market, '
'ROW_NUMBER() OVER (ORDER BY usd_price DESC) AS rank, '
'json_agg(json_build_object('
' \'asset_id\', asset_id, \'name\', an.name, \'mint\', mint, \'image\', ai.image, '
' \'template_id\', template_id'
')) as assets '
'FROM sales t '
'LEFT JOIN collections c USING (collection) '
'LEFT JOIN assets a ON a.asset_id = t.asset_ids[1] '
'LEFT JOIN names an ON a.name_id = an.name_id '
'LEFT JOIN names cn ON c.name_id = cn.name_id '
'LEFT JOIN images ai ON a.image_id = ai.name_id '
'LEFT JOIN images ci ON c.image_id = ci.name_id '
'WHERE TRUE {time_clause} {collection_clause} {template_clause} '
'AND NOT c.blacklisted '
'GROUP BY 1, 2, 3, 4, 5, 6, 7, 8, 9 '
'ORDER BY usd_price DESC LIMIT :limit OFFSET :offset '.format(
time_clause=' AND t.timestamp > (NOW() - INTERVAL :interval) at time zone \'utc\''
if days and int(days) > 0 else '',
template_clause=' AND template_id = :template_id ' if template_id else '',
collection_clause=' AND t.collection = :collection ' if collection else ''
), {
'interval': '{} days'.format(days), 'collection': collection, 'limit': limit, 'offset': offset,
'template_id': template_id
}
)
sales = []
for row in res:
sales.append(
{
'collection': {
'name': row.author,
'displayName': row.name,
'image': row.collection_image,
},
'assets': _format_assets(row.assets),
'days': days,
'price': row.price,
'usdPrice': row.usd_price,
'buyer': row.buyer,
'seller': row.seller,
'tx': row.buy_transaction_id,
'rank': row.rank
}
)
return sales
except SQLAlchemyError as e:
logging.error(e)
session.rollback()
raise e
finally:
session.remove()
@cache.memoize(timeout=60)
def get_attribute_asset_analytics_schema(asset_id, collection, schema):
session = create_session()
try:
res = session.execute(
'SELECT asu.total, asu.total_schema, af.*, att.*, t.idata, c.name AS display_name, a.rank, a.rarity_score, '
'c.image AS collection_image, t.template_id, t.category '
'FROM pfp_assets a '
'LEFT JOIN templates t USING (template_id) '
'LEFT JOIN collections c ON t.collection = c.collection '
'INNER JOIN attribute_summaries asu ON attribute_id = ANY(a.attribute_ids) '
'LEFT JOIN attribute_floors_mv af USING(attribute_id) '
'LEFT JOIN attributes att USING(attribute_id) '
'WHERE a.collection = :collection AND a.schema = :schema {asset_clause}'.format(
asset_clause=' AND a.asset_id = :asset_id' if asset_id else ' AND a.asset_id = (SELECT asset_id FROM attribute_assets WHERE author = :collection AND schema = :schema AND rank = 1 LIMIT 1) '
), {'collection': collection, 'schema': schema, 'asset_id': asset_id}
)
template = None
collection = None
attributes = []
if res and res.rowcount > 0:
for attribute in res:
if not template:
template = json.loads(attribute['idata']) if attribute['idata'] else {}
template['template_id'] = attribute['template_id']
template['schema'] = attribute['category']
template['rarityScore'] = attribute['rarity_score']
template['rank'] = attribute['rank']
collection = {
'name': attribute.author,
'displayName': attribute.display_name,
'image': attribute.collection_image,
}
attributes.append({
'name': attribute['attribute_name'],
'value': attribute['string_value'] if attribute['string_value']
else attribute['int_value'] if attribute['int_value'] or attribute['int_value'] == 0
else float(attribute['float_value']) if attribute['float_value'] or attribute['float_value'] == 0
else attribute['bool_value'],
'total': attribute['total'],
'percentage': attribute['total'] / attribute['total_schema'] if attribute['total_schema'] and attribute['total'] else 0,
'waxFloor': attribute['floor'],
'usdFloor': attribute['usd_floor'],
})
return {
'template': template,
'attributes': attributes,
'collection': collection
}
else:
return None
except SQLAlchemyError as e:
logging.error(e)
session.rollback()
raise e
finally:
session.remove()
@cache.memoize(timeout=60)
def get_pfp_asset_analytics(asset_id, template_id):
session = create_session()
if not asset_id and not template_id:
return None
try:
res = session.execute(
'SELECT ast.total, ast.total_schema, af.*, att.*, td.data, cn.name AS display_name, a.rank, a.rarity_score,'
'ci.image AS collection_image, t.template_id, t.schema '
'FROM pfp_assets a '
'LEFT JOIN templates t USING (template_id) '
'LEFT JOIN data td ON t.immutable_data_id = td.data_id '
'LEFT JOIN collections c ON a.collection = c.collection '
'LEFT JOIN names cn ON c.name_id = cn.name_id '
'LEFT JOIN images ci ON c.image_id = ci.image_id '
'INNER JOIN attribute_stats ast ON attribute_id = ANY(a.attribute_ids) '
'LEFT JOIN attribute_floors_mv af USING(attribute_id) '
'LEFT JOIN attributes att USING(attribute_id) '
'WHERE TRUE {template_clause} {asset_clause}'.format(
template_clause=' AND template_id = :template_id ' if template_id else '',
asset_clause=' AND a.asset_id = :asset_id' if asset_id else (
' AND a.asset_id = (SELECT asset_id FROM pfp_assets '
'WHERE template_id = :template_id AND rank = 1 LIMIT 1) '
)
), {'template_id': template_id, 'asset_id': asset_id}
)
template = None
collection = None
attributes = []
if res and res.rowcount > 0:
for attribute in res:
if not template:
template = _parse_data_object(json.loads(attribute['data'])) if attribute['data'] else {}
template['template_id'] = attribute['template_id']
template['schema'] = attribute['schema']
template['rarityScore'] = attribute['rarity_score']
template['rank'] = attribute['rank']
collection = {
'name': attribute.collection,
'displayName': attribute.display_name,
'image': attribute.collection_image,
}
attributes.append({
'name': attribute['attribute_name'],
'value': attribute['string_value'] if attribute['string_value']
else attribute['int_value'] if attribute['int_value'] or attribute['int_value'] == 0
else float(attribute['float_value']) if attribute['float_value'] or attribute['float_value'] == 0
else attribute['bool_value'],
'total': attribute['total'],
'percentage': attribute['total'] / attribute['total_schema'] if attribute['total_schema'] else 0,
'waxFloor': attribute['floor_wax'],
'usdFloor': attribute['floor_usd'],
})
return {
'template': template,
'attributes': attributes,
'collection': collection
}
else:
return None
except SQLAlchemyError as e:
logging.error(e)
session.rollback()
raise e
finally:
session.remove()
@cache.memoize(timeout=300)
def get_similar_collections(collection):
session = create_session()
try:
sql = (
'SELECT d.collection, ci.image, cn.name, rank_val '
'FROM (SELECT collection, SUM(1 - (rank/10)) AS rank_val '
'FROM ('
' SELECT owner, collection, num_assets, wax_value, rank() OVER ('
' PARTITION BY owner ORDER BY wax_value DESC NULLS LAST'
' )'
' FROM collection_users_mv '
' WHERE owner IN ('
' SELECT owner FROM collection_users_mv '
' WHERE collection = :collection '
' AND wax_value > (SELECT AVG(wax_value) '
' FROM collection_users_mv WHERE collection = :collection)'
' ORDER BY wax_value DESC NULLS LAST LIMIT 1000) '
' AND collection != :collection AND wax_value > 50) b '
'WHERE rank < 10 GROUP BY 1 ORDER BY 2 DESC NULLS LAST) d '
'LEFT JOIN collections c USING (collection) '
'LEFT JOIN names cn ON c.name_id = cn.name_id '
'LEFT JOIN images ci ON c.image_id = ci.image_id '
'ORDER BY 4 DESC LIMIT 9'
)
res = session.execute(
sql, {
'collection': collection
}
)
collections = []
for collection in res:
collections.append({
'collection': collection['collection'],
'name': collection['name'],
'image': collection['image']
})
return collections
except SQLAlchemyError as e:
logging.error(e)
session.rollback()
raise e
finally:
session.remove()
@cache.memoize(timeout=60)
def get_attribute_analytics(template_id):
session = create_session()
try:
res = session.execute(
'SELECT asu.total, asu.total_schema, af.*, a.*, t.*, c.name AS display_name, c.image AS collection_image '
'FROM templates t '
'LEFT JOIN collections c ON t.author = c.collection_name '
'INNER JOIN attribute_summaries asu ON attribute_id = ANY(attribute_ids) '
'LEFT JOIN attribute_floors_mv af USING(attribute_id) '
'LEFT JOIN attributes a USING(attribute_id) '
'WHERE template_id = :template_id',
{'template_id': template_id}
)
template = None
collection = None
attributes = []
if res and res.rowcount > 0:
for attribute in res:
if not template:
template = json.loads(attribute['idata'])
template['template_id'] = attribute['template_id']
template['schema'] = attribute['category']
collection = {
'name': attribute.author,
'displayName': attribute.display_name,
'image': attribute.collection_image,
}
attributes.append({
'name': attribute['attribute_name'],
'value': attribute['string_value'] if attribute['string_value']
else attribute['int_value'] if attribute['int_value'] or attribute['int_value'] == 0
else float(attribute['float_value']) if attribute['float_value'] or attribute['float_value'] == 0
else attribute['bool_value'],
'total': attribute['total'],
'percentage': attribute['total'] / attribute['total_schema'] if attribute['total_schema'] > 0 else 0,
'waxFloor': attribute['floor'],
'usdFloor': attribute['usd_floor']
})
else:
return None
return {
'template': template,
'attributes': attributes,
'collection': collection
}
except SQLAlchemyError as e:
logging.error(e)
session.rollback()
raise e
finally:
session.remove()
@cache.memoize(timeout=60)
def get_floor(template_id):
session = create_session()
try:
total_res = session.execute(
'SELECT COUNT(1) AS total, td.data, t.attribute_ids '
'FROM templates t '
'LEFT JOIN data td ON t.immutable_data_id = td.data_id '
'WHERE t.template_id = :template_id GROUP BY 2, 3',
{'template_id': template_id}
).first()
template_data = _parse_data_object(json.loads(total_res['data']))
template = session.execute(
'SELECT td.data, template_id, t.schema, tb.collection, cn.name, ci.image, floor_price '
'FROM template_floor_prices_mv tb '
'INNER JOIN collections c USING (collection) '
'LEFT JOIN names cn ON c.name_id = cn.name_id '
'LEFT JOIN images ci ON c.image_id = ci.image_id '