-
Notifications
You must be signed in to change notification settings - Fork 129
/
assets.go
1199 lines (1093 loc) · 34.9 KB
/
assets.go
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
package models
import (
"context"
"database/sql"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/diadata-org/diadata/pkg/dia"
"github.com/ethereum/go-ethereum/common"
"github.com/go-redis/redis"
"github.com/jackc/pgtype"
"github.com/jackc/pgx/v4"
)
// GetKeyAsset returns an asset's key in the redis cache of the asset table.
// @assetID refers to the primary key asset_id in the asset table.
func (rdb *RelDB) GetKeyAsset(asset dia.Asset) (string, error) {
ID, err := rdb.GetAssetID(asset)
if err != nil {
return "", err
}
return keyAssetCache + ID, nil
}
// -------------------------------------------------------------
// Postgres methods
// -------------------------------------------------------------
// -------------------------------------------------------------
// asset TABLE methods
// -------------------------------------------------------------
// SetAsset stores an asset into postgres.
func (rdb *RelDB) SetAsset(asset dia.Asset) error {
query := fmt.Sprintf("INSERT INTO %s (symbol,name,address,decimals,blockchain) VALUES ($1,$2,$3,$4,$5) ON CONFLICT (address,blockchain) DO NOTHING", assetTable)
_, err := rdb.postgresClient.Exec(context.Background(), query, asset.Symbol, asset.Name, asset.Address, strconv.Itoa(int(asset.Decimals)), asset.Blockchain)
if err != nil {
return err
}
return nil
}
// GetAssetID returns the unique identifier of @asset in postgres table asset, if the entry exists.
func (rdb *RelDB) GetAssetID(asset dia.Asset) (ID string, err error) {
query := fmt.Sprintf("SELECT asset_id FROM %s WHERE address=$1 AND blockchain=$2", assetTable)
err = rdb.postgresClient.QueryRow(context.Background(), query, asset.Address, asset.Blockchain).Scan(&ID)
if err != nil {
return
}
return
}
func (rdb *RelDB) GetAssetMap(asset_id string) (ID string, err error) {
query := fmt.Sprintf("SELECT group_id FROM %s WHERE asset_id=$1", assetIdent)
err = rdb.postgresClient.QueryRow(context.Background(), query, asset_id).Scan(&ID)
if err != nil {
return
}
return
}
func (rdb *RelDB) GetAssetByGroupID(group_id string) (assets []dia.Asset, err error) {
var (
rows pgx.Rows
decimals sql.NullInt64
)
query := fmt.Sprintf("SELECT symbol,name,address,blockchain,decimals FROM %s WHERE asset_id in (select asset_id from %s where group_id=$1)", assetTable, assetIdent)
rows, err = rdb.postgresClient.Query(context.Background(), query, group_id)
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var asset dia.Asset
err := rows.Scan(&asset.Symbol, &asset.Name, &asset.Address, &asset.Blockchain, &decimals)
if err != nil {
log.Error(err)
}
if decimals.Valid {
asset.Decimals = uint8(decimals.Int64)
}
// asset.Blockchain = blockchain
assets = append(assets, asset)
}
return
}
// SetAsset stores an asset into postgres.
func (rdb *RelDB) InsertAssetMap(group_id string, asset_id string) error {
query := fmt.Sprintf("INSERT INTO %s (group_id,asset_id) VALUES ($1,$2)", assetIdent)
log.Println("query", query)
_, err := rdb.postgresClient.Exec(context.Background(), query, group_id, asset_id)
if err != nil {
return err
}
return nil
}
func (rdb *RelDB) InsertNewAssetMap(asset_id string) error {
query := fmt.Sprintf("INSERT INTO %s (asset_id) VALUES ($1)", assetIdent)
log.Println("query", query)
_, err := rdb.postgresClient.Exec(context.Background(), query, asset_id)
if err != nil {
return err
}
return nil
}
// GetAsset is the standard method in order to uniquely retrieve an asset from asset table.
func (rdb *RelDB) GetAsset(address, blockchain string) (asset dia.Asset, err error) {
cachedAsset, errCache := rdb.GetAssetCache(blockchain, address)
if errCache == nil {
asset = cachedAsset
return
}
var decimals sql.NullInt64
query := fmt.Sprintf("SELECT symbol,name,address,decimals,blockchain FROM %s WHERE address=$1 AND blockchain=$2", assetTable)
err = rdb.postgresClient.QueryRow(context.Background(), query, address, blockchain).Scan(
&asset.Symbol,
&asset.Name,
&asset.Address,
&decimals,
&asset.Blockchain,
)
if err != nil {
return
}
if decimals.Valid {
asset.Decimals = uint8(decimals.Int64)
}
return
}
// GetAssetByID returns an asset by its uuid
func (rdb *RelDB) GetAssetByID(assetID string) (asset dia.Asset, err error) {
var decimals sql.NullInt64
query := fmt.Sprintf("SELECT symbol,name,address,decimals,blockchain FROM %s WHERE asset_id=$1", assetTable)
err = rdb.postgresClient.QueryRow(context.Background(), query, assetID).Scan(&asset.Symbol, &asset.Name, &asset.Address, &decimals, &asset.Blockchain)
if err != nil {
return
}
if decimals.Valid {
asset.Decimals = uint8(decimals.Int64)
}
return
}
// GetAllAssets returns all assets on @blockchain from asset table.
func (rdb *RelDB) GetAllAssets(blockchain string) (assets []dia.Asset, err error) {
var rows pgx.Rows
query := fmt.Sprintf("SELECT symbol,name,address,decimals FROM %s WHERE blockchain=$1", assetTable)
rows, err = rdb.postgresClient.Query(context.Background(), query, blockchain)
if err != nil {
return
}
defer rows.Close()
var decimals sql.NullInt64
for rows.Next() {
var asset dia.Asset
err := rows.Scan(&asset.Symbol, &asset.Name, &asset.Address, &decimals)
if err != nil {
log.Error(err)
}
if decimals.Valid {
asset.Decimals = uint8(decimals.Int64)
}
asset.Blockchain = blockchain
assets = append(assets, asset)
}
return
}
// GetAssetsBySymbolName returns a (possibly multiple) dia.Asset by its symbol and name from postgres.
// If @name is an empty string, it returns all assets with @symbol.
// If @symbol is an empty string, it returns all assets with @name.
func (rdb *RelDB) GetAssetsBySymbolName(symbol, name string) (assets []dia.Asset, err error) {
var (
decimals sql.NullInt64
rows pgx.Rows
query string
)
if name == "" {
query = fmt.Sprintf(`
SELECT symbol,name,address,decimals,blockchain
FROM %s a
INNER JOIN %s av
ON av.asset_id=a.asset_id
WHERE av.volume>0
AND av.time_stamp IS NOT NULL
AND symbol ILIKE '%s%%'
ORDER BY av.volume DESC`,
assetTable,
assetVolumeTable,
symbol,
)
} else if symbol == "" {
query = fmt.Sprintf(`
SELECT symbol,name,address,decimals,blockchain
FROM %s a
INNER JOIN %s av
ON av.asset_id=a.asset_id
WHERE av.volume>0
AND av.time_stamp IS NOT NULL
AND name ILIKE '%s%%'
ORDER BY av.volume DESC`,
assetTable,
assetVolumeTable,
symbol,
)
} else {
query = fmt.Sprintf(`
SELECT symbol,name,address,decimals,blockchain
FROM %s a
INNER JOIN %s av
ON av.asset_id=a.asset_id
WHERE av.volume>0
AND av.time_stamp IS NOT NULL
AND (symbol ILIKE '%s%%' OR name ILIKE '%s%%')
ORDER BY av.volume DESC`,
assetTable,
assetVolumeTable,
name,
symbol,
)
}
if err != nil {
return
}
rows, err = rdb.postgresClient.Query(context.Background(), query)
log.Infoln("GetAssetsBySymbolName query", query)
defer rows.Close()
for rows.Next() {
var asset dia.Asset
err = rows.Scan(&asset.Symbol, &asset.Name, &asset.Address, &decimals, &asset.Blockchain)
if err != nil {
return
}
if decimals.Valid {
asset.Decimals = uint8(decimals.Int64)
}
assets = append(assets, asset)
}
return
}
// GetAssetsByAddress returns a (possibly multiple) dia.Asset by its address from postgres.
func (rdb *RelDB) GetAssetsByAddress(address string) (assets []dia.Asset, err error) {
var (
decimals sql.NullInt64
rows pgx.Rows
)
query := fmt.Sprintf(`
SELECT symbol,name,address,decimals,blockchain
FROM %s a
INNER JOIN %s av
ON a.asset_id=av.asset_id
WHERE av.volume>0
AND av.time_stamp IS NOT NULL
AND address ILIKE '%s%%'
ORDER BY av.volume DESC`,
assetTable,
assetVolumeTable,
address,
)
rows, err = rdb.postgresClient.Query(context.Background(), query)
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var asset dia.Asset
err = rows.Scan(&asset.Symbol, &asset.Name, &asset.Address, &decimals, &asset.Blockchain)
if err != nil {
return
}
if decimals.Valid {
asset.Decimals = uint8(decimals.Int64)
}
assets = append(assets, asset)
}
return
}
// GetFiatAssetBySymbol returns a fiat asset by its symbol. This is possible as
// fiat currencies are uniquely defined by their symbol.
func (rdb *RelDB) GetFiatAssetBySymbol(symbol string) (asset dia.Asset, err error) {
var decimals sql.NullInt64
query := fmt.Sprintf("SELECT name,address,decimals FROM %s WHERE symbol=$1 AND blockchain='Fiat'", assetTable)
err = rdb.postgresClient.QueryRow(context.Background(), query, symbol).Scan(&asset.Name, &asset.Address, &decimals)
if err != nil {
return
}
if decimals.Valid {
asset.Decimals = uint8(decimals.Int64)
}
asset.Symbol = symbol
asset.Blockchain = "Fiat"
// TO DO: Get Blockchain by name from postgres and add to asset
return
}
// IdentifyAsset looks for all assets in postgres which match the non-null fields in @asset
// Comment 1: The only critical field is @Decimals, as this is initialized with 0, while an
// asset is allowed to have zero decimals as well (for instance sngls, trxc).
// Comment 2: Should we add a preprocessing step in which notation is corrected corresponding
// to the notation in the underlying contract on the blockchain?
// Comment 3: Can we improve this? How to treat cases like CoinBase emitting symbol name
// 'Wrapped Bitcoin' instead of the correct 'Wrapped BTC', or 'United States Dollar' instead
// of 'United States dollar'? On idea would be to add a table with alternative names for
// symbol tickers, so WBTC -> [Wrapped Bitcoin, Wrapped bitcoin, Wrapped BTC,...]
func (rdb *RelDB) IdentifyAsset(asset dia.Asset) (assets []dia.Asset, err error) {
query := fmt.Sprintf("SELECT symbol,name,address,decimals,blockchain FROM %s WHERE ", assetTable)
var and string
if asset.Symbol != "" {
query += fmt.Sprintf("symbol='%s'", asset.Symbol)
and = " AND "
}
if asset.Name != "" {
query += fmt.Sprintf(and+"name='%s'", asset.Name)
and = " AND "
}
if asset.Address != "" {
query += fmt.Sprintf(and+"address='%s'", common.HexToAddress(asset.Address).Hex())
and = " AND "
}
if asset.Decimals != 0 {
query += fmt.Sprintf(and+"decimals='%d'", asset.Decimals)
and = " AND "
}
if asset.Blockchain != "" {
query += fmt.Sprintf(and+"blockchain='%s'", asset.Blockchain)
}
rows, err := rdb.postgresClient.Query(context.Background(), query)
if err != nil {
return
}
defer rows.Close()
var decimals sql.NullInt64
for rows.Next() {
asset := dia.Asset{}
err = rows.Scan(&asset.Symbol, &asset.Name, &asset.Address, &decimals, &asset.Blockchain)
if err != nil {
return
}
if decimals.Valid {
asset.Decimals = uint8(decimals.Int64)
}
assets = append(assets, asset)
}
return
}
// -------------------------------------------------------------
// exchangesymbol TABLE methods
// -------------------------------------------------------------
// SetExchangeSymbol writes unique data into exchangesymbol table if not yet in there.
func (rdb *RelDB) SetExchangeSymbol(exchange string, symbol string) error {
query := fmt.Sprintf(`
INSERT INTO %s (symbol,exchange)
SELECT $1,$2
WHERE NOT EXISTS
(SELECT 1 FROM exchangesymbol WHERE symbol=$1 AND exchange=$2)
`, exchangesymbolTable)
_, err := rdb.postgresClient.Exec(context.Background(), query, symbol, exchange)
if err != nil {
return err
}
return nil
}
func (rdb *RelDB) GetExchangeSymbol(exchange string, symbol string) (asset dia.Asset, err error) {
var decimals sql.NullInt64
query := fmt.Sprintf(`
SELECT a.symbol,a.name,a.address,a.blockchain,a.decimals
FROM %s es
INNER JOIN %s a
ON es.asset_id=a.asset_id
WHERE es.exchange=$1
AND es.symbol ILIKE $2
`,
exchangesymbolTable,
assetTable,
)
err = rdb.postgresClient.QueryRow(context.Background(), query, exchange, symbol).Scan(
&asset.Symbol,
&asset.Name,
&asset.Address,
&asset.Blockchain,
&decimals,
)
if err != nil {
return
}
if decimals.Valid {
asset.Decimals = uint8(decimals.Int64)
}
return
}
// GetAssets returns all assets which share the symbol ticker @symbol.
func (rdb *RelDB) GetAssets(symbol string) (assets []dia.Asset, err error) {
query := fmt.Sprintf("SELECT symbol,name,address,decimals,blockchain FROM %s WHERE symbol=$1 ", assetTable)
var rows pgx.Rows
rows, err = rdb.postgresClient.Query(context.Background(), query, symbol)
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var decimals sql.NullInt64
asset := dia.Asset{}
err = rows.Scan(&asset.Symbol, &asset.Name, &asset.Address, &decimals, &asset.Blockchain)
if err != nil {
return
}
if decimals.Valid {
asset.Decimals = uint8(decimals.Int64)
}
assets = append(assets, asset)
}
return
}
// GetAssetExchnage returns all assets which share the symbol ticker @symbol.
func (rdb *RelDB) GetAssetExchange(symbol string) (exchanges []string, err error) {
query := fmt.Sprintf(`
SELECT exchange
FROM %s
INNER JOIN %s
ON asset.asset_id = exchangesymbol.asset_id
WHERE exchangesymbol.symbol = $1
`, exchangesymbolTable, assetTable)
var rows pgx.Rows
rows, err = rdb.postgresClient.Query(context.Background(), query, symbol)
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var exchange string
err = rows.Scan(&exchange)
if err != nil {
return
}
exchanges = append(exchanges, exchange)
}
return
}
// GetUnverifiedExchangeSymbols returns all symbols from @exchange which haven't been verified yet.
func (rdb *RelDB) GetUnverifiedExchangeSymbols(exchange string) (symbols []string, err error) {
query := fmt.Sprintf("SELECT symbol FROM %s WHERE exchange=$1 AND verified=false ORDER BY symbol ASC", exchangesymbolTable)
var rows pgx.Rows
rows, err = rdb.postgresClient.Query(context.Background(), query, exchange)
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
symbol := ""
err = rows.Scan(&symbol)
if err != nil {
return []string{}, err
}
symbols = append(symbols, symbol)
}
return
}
// GetExchangeSymbols returns all symbols traded on @exchange.
// If @exchange is the empty string, all symbols are returned.
// If @substring is not the empty string, all symbols that begin with @substring (case insensitive) are returned.
func (rdb *RelDB) GetExchangeSymbols(exchange string, substring string) (symbols []string, err error) {
var query string
var rows pgx.Rows
if exchange != "" {
if substring != "" {
query = fmt.Sprintf("SELECT symbol FROM %s WHERE exchange=$1 AND symbol ILIKE '%s%%'", exchangesymbolTable, substring)
rows, err = rdb.postgresClient.Query(context.Background(), query, exchange)
} else {
query = fmt.Sprintf("SELECT symbol FROM %s WHERE exchange=$1", exchangesymbolTable)
rows, err = rdb.postgresClient.Query(context.Background(), query, exchange)
}
} else {
if substring != "" {
query = fmt.Sprintf("SELECT symbol FROM %s WHERE symbol ILIKE '%s%%'", exchangesymbolTable, substring)
log.Info("query: ", query)
rows, err = rdb.postgresClient.Query(context.Background(), query)
} else {
query = fmt.Sprintf("SELECT symbol FROM %s", exchangesymbolTable)
rows, err = rdb.postgresClient.Query(context.Background(), query)
}
}
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
symbol := ""
err = rows.Scan(&symbol)
if err != nil {
return []string{}, err
}
symbols = append(symbols, symbol)
}
return
}
// VerifyExchangeSymbol verifies @symbol on @exchange and maps it uniquely to @assetID in asset table.
// It returns true if symbol,exchange is present and succesfully updated.
func (rdb *RelDB) VerifyExchangeSymbol(exchange string, symbol string, assetID string) (bool, error) {
query := fmt.Sprintf("UPDATE %s SET verified=true,asset_id=$1 WHERE symbol=$2 AND exchange=$3", exchangesymbolTable)
resp, err := rdb.postgresClient.Exec(context.Background(), query, assetID, symbol, exchange)
if err != nil {
return false, err
}
var success bool
respSlice := strings.Split(string(resp), " ")
numUpdates := respSlice[1]
if numUpdates != "0" {
success = true
}
return success, nil
}
// GetExchangeSymbolAssetID returns the ID of the unique asset associated to @symbol on @exchange
// in case the symbol is verified. An empty string if not.
func (rdb *RelDB) GetExchangeSymbolAssetID(exchange string, symbol string) (assetID string, verified bool, err error) {
var uuid pgtype.UUID
query := fmt.Sprintf("SELECT asset_id, verified FROM %s WHERE symbol=$1 AND exchange=$2", exchangesymbolTable)
err = rdb.postgresClient.QueryRow(context.Background(), query, symbol, exchange).Scan(&uuid, &verified)
if err != nil {
return
}
val, err := uuid.Value()
if err != nil {
log.Error(err)
}
if val != nil {
assetID = val.(string)
}
return
}
// -------------------------------------------------------------
// Blockchain methods
// -------------------------------------------------------------
func (rdb *RelDB) SetBlockchain(blockchain dia.BlockChain) (err error) {
fields := fmt.Sprintf("INSERT INTO %s (name,genesisdate,nativetoken_id,verificationmechanism,chain_id) VALUES ", blockchainTable)
values := "($1,$2,(SELECT asset_id FROM asset WHERE address=$3 AND blockchain=$1),$4,NULLIF($5,'')) "
conflict := `
ON CONFLICT (name)
DO UPDATE SET
genesisdate=$2,verificationmechanism=$4,chain_id=NULLIF($5,''),nativetoken_id=(SELECT asset_id FROM asset WHERE address=$3 AND blockchain=$1)
`
query := fields + values + conflict
_, err = rdb.postgresClient.Exec(context.Background(), query,
blockchain.Name,
blockchain.GenesisDate,
blockchain.NativeToken.Address,
blockchain.VerificationMechanism,
blockchain.ChainID,
)
if err != nil {
return err
}
return nil
}
func (rdb *RelDB) GetBlockchain(name string) (blockchain dia.BlockChain, err error) {
query := fmt.Sprintf(`
SELECT genesisdate,verificationmechanism,chain_id,address,symbol
FROM %s
INNER JOIN %s
ON %s.nativetoken_id=%s.asset_id
WHERE %s.name=$1
`, blockchainTable, assetTable, blockchainTable, assetTable, blockchainTable)
err = rdb.postgresClient.QueryRow(context.Background(), query, name).Scan(
&blockchain.GenesisDate,
&blockchain.VerificationMechanism,
&blockchain.ChainID,
&blockchain.NativeToken.Address,
&blockchain.NativeToken.Symbol,
)
if err != nil {
return
}
blockchain.Name = name
return
}
// GetAllBlockchains returns all blockchains from the blockchain table.
// If fullAsset=true it returns the complete native token as asset, otherwise only its symbol string.
func (rdb *RelDB) GetAllBlockchains(fullAsset bool) ([]dia.BlockChain, error) {
var (
blockchains []dia.BlockChain
query string
)
if fullAsset {
query = fmt.Sprintf(`
SELECT b.name,b.genesisdate,a.Symbol,a.Name,a.Address,a.Decimals,b.verificationmechanism,b.chain_id
FROM %s b
LEFT JOIN %s a
ON nativetoken_id = a.asset_id
`, blockchainTable, assetTable)
} else {
query = fmt.Sprintf(`
SELECT b.name,b.genesisdate,a.Symbol,b.verificationmechanism,b.chain_id
FROM %s b
LEFT JOIN %s a
ON nativetoken_id = a.asset_id
`, blockchainTable, assetTable)
}
rows, err := rdb.postgresClient.Query(context.Background(), query)
if err != nil {
return []dia.BlockChain{}, err
}
defer rows.Close()
for rows.Next() {
var (
blockchain dia.BlockChain
genDate sql.NullFloat64
symbol sql.NullString
verifMechanism sql.NullString
chainID sql.NullString
// fullAsset
name sql.NullString
address sql.NullString
decimals sql.NullInt64
)
if fullAsset {
err = rows.Scan(
&blockchain.Name,
&genDate,
&symbol,
&name,
&address,
&decimals,
&verifMechanism,
&chainID,
)
} else {
err = rows.Scan(
&blockchain.Name,
&genDate,
&symbol,
&verifMechanism,
&chainID,
)
}
if err != nil {
return []dia.BlockChain{}, err
}
if genDate.Valid {
blockchain.GenesisDate = int64(genDate.Float64)
}
if symbol.Valid {
blockchain.NativeToken.Symbol = symbol.String
}
if verifMechanism.Valid {
blockchain.VerificationMechanism = dia.VerificationMechanism(verifMechanism.String)
}
if chainID.Valid {
blockchain.ChainID = chainID.String
}
if fullAsset {
if name.Valid {
blockchain.NativeToken.Name = name.String
}
if address.Valid {
blockchain.NativeToken.Address = address.String
}
if decimals.Valid {
blockchain.NativeToken.Decimals = uint8(decimals.Int64)
}
blockchain.NativeToken.Blockchain = blockchain.Name
}
blockchains = append(blockchains, blockchain)
}
return blockchains, nil
}
// GetAllAssetsBlockchains returns all blockchain names existent in the asset table.
func (rdb *RelDB) GetAllAssetsBlockchains() ([]string, error) {
var blockchains []string
query := fmt.Sprintf("SELECT DISTINCT blockchain FROM %s WHERE name!='' ORDER BY blockchain ASC", assetTable)
rows, err := rdb.postgresClient.Query(context.Background(), query)
if err != nil {
return []string{}, err
}
defer rows.Close()
for rows.Next() {
var blockchain string
err := rows.Scan(&blockchain)
if err != nil {
return []string{}, err
}
blockchains = append(blockchains, blockchain)
}
return blockchains, nil
}
// -------------------------------------------------------------
// General methods
// -------------------------------------------------------------
// GetPage returns assets per page number. @hasNext is true iff there is a non-empty next page.
func (rdb *RelDB) GetPage(pageNumber uint32) (assets []dia.Asset, hasNextPage bool, err error) {
pagesize := rdb.pagesize
skip := pagesize * pageNumber
rows, err := rdb.postgresClient.Query(context.Background(), "SELECT symbol,name,address,decimals,blockchain FROM asset LIMIT $1 OFFSET $2 ", pagesize, skip)
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
fmt.Println("---")
var asset dia.Asset
err = rows.Scan(&asset.Symbol, &asset.Name, &asset.Address, &asset.Decimals, &asset.Blockchain)
if err != nil {
return
}
assets = append(assets, asset)
}
// Last page (or empty page)
if len(rows.RawValues()) < int(pagesize) {
hasNextPage = false
return
}
// No next page
nextPageRows, err := rdb.postgresClient.Query(context.Background(), "SELECT symbol,name,address,decimals,blockchain FROM asset LIMIT $1 OFFSET $2 ", pagesize, skip+1)
if len(nextPageRows.RawValues()) == 0 {
hasNextPage = false
return
}
defer nextPageRows.Close()
hasNextPage = true
return
}
// Count returns the number of assets stored in postgres
func (rdb *RelDB) Count() (count uint32, err error) {
err = rdb.postgresClient.QueryRow(context.Background(), "SELECT COUNT(*) FROM asset").Scan(&count)
if err != nil {
return
}
return
}
// -------------------------------------------------------------
// Caching layer
// -------------------------------------------------------------
// SetAssetCache stores @asset in redis, using its primary key in postgres as key.
// As a consequence, @asset is only cached iff it exists in postgres.
func (rdb *RelDB) SetAssetCache(asset dia.Asset) error {
return rdb.redisClient.Set(keyAssetCache+asset.Identifier(), &asset, 0).Err()
}
// GetAssetCache returns an asset by its asset_id as defined in asset table in postgres
func (rdb *RelDB) GetAssetCache(blockchain string, address string) (asset dia.Asset, err error) {
asset.Blockchain = blockchain
asset.Address = address
err = rdb.redisClient.Get(keyAssetCache + asset.Identifier()).Scan(&asset)
return
}
// CountCache returns the number of assets in the cache
func (rdb *RelDB) CountCache() (uint32, error) {
keysPattern := keyAssetCache + "*"
allAssets := rdb.redisClient.Keys(keysPattern).Val()
return uint32(len(allAssets)), nil
}
// -------------- Caching exchange pairs -------------------
// SetExchangePairCache stores @pairs in redis
func (rdb *RelDB) SetExchangePairCache(exchange string, pair dia.ExchangePair) error {
key := keyExchangePairCache + exchange + "_" + pair.ForeignName
return rdb.redisClient.Set(key, &pair, 0).Err()
}
// GetExchangePairCache returns an exchange pair by @exchange and @foreigName
func (rdb *RelDB) GetExchangePairCache(exchange string, foreignName string) (dia.ExchangePair, error) {
exchangePair := dia.ExchangePair{}
err := rdb.redisClient.Get(keyExchangePairCache + exchange + "_" + foreignName).Scan(&exchangePair)
if err != nil {
if !errors.Is(err, redis.Nil) {
log.Errorf("GetExchangePairCache on %s with foreign name %s: %v\n", exchange, foreignName, err)
}
return exchangePair, err
}
return exchangePair, nil
}
func (rdb *RelDB) SetAssetVolume24H(asset dia.Asset, volume float64, timestamp time.Time) error {
initialStr := fmt.Sprintf("INSERT INTO %s (asset_id,volume,time_stamp) VALUES ", assetVolumeTable)
substring := fmt.Sprintf(
"((SELECT asset_id FROM asset WHERE address='%s' AND blockchain='%s'),%f,to_timestamp(%v))",
asset.Address,
asset.Blockchain,
volume,
timestamp.Unix(),
)
conflict := " ON CONFLICT (asset_id) DO UPDATE SET volume=EXCLUDED.volume,time_stamp=EXCLUDED.time_stamp"
query := initialStr + substring + conflict
_, err := rdb.postgresClient.Exec(context.Background(), query)
if err != nil {
return err
}
return nil
}
func (rdb *RelDB) GetLastAssetVolume24H(asset dia.Asset) (volume float64, err error) {
query := fmt.Sprintf("SELECT volume FROM %s INNER JOIN %s ON assetvolume.asset_id = asset.asset_id WHERE address=$1 AND blockchain=$2", assetVolumeTable, assetTable)
err = rdb.postgresClient.QueryRow(context.Background(), query, asset.Address, asset.Blockchain).Scan(&volume)
return
}
func (rdb *RelDB) GetTopAssetByVolume(symbol string) (assets []dia.Asset, err error) {
query := fmt.Sprintf(`
SELECT symbol,name,address,decimals,blockchain
FROM %s
INNER JOIN %s
ON asset.asset_id = assetvolume.asset_id
WHERE symbol=$1
ORDER BY volume DESC
`, assetTable, assetVolumeTable)
var rows pgx.Rows
rows, err = rdb.postgresClient.Query(context.Background(), query, symbol)
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var decimals sql.NullInt64
asset := dia.Asset{}
err = rows.Scan(&asset.Symbol, &asset.Name, &asset.Address, &decimals, &asset.Blockchain)
if err != nil {
return
}
if decimals.Valid {
asset.Decimals = uint8(decimals.Int64)
}
assets = append(assets, asset)
}
return
}
func (rdb *RelDB) GetByLimit(limit, skip uint32) (assets []dia.Asset, assetIds []string, err error) {
rows, err := rdb.postgresClient.Query(
context.Background(),
"SELECT asset_id,symbol,name,address,decimals,blockchain FROM asset LIMIT $1 OFFSET $2",
limit,
skip,
)
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var (
decimals sql.NullInt64
assetID string
asset dia.Asset
)
err = rows.Scan(&assetID, &asset.Symbol, &asset.Name, &asset.Address, &decimals, &asset.Blockchain)
if err != nil {
return
}
if decimals.Valid {
asset.Decimals = uint8(decimals.Int64)
}
assets = append(assets, asset)
assetIds = append(assetIds, assetID)
}
return
}
// GetAssetsWithVolByBlockchain returns all assets from assetvolume table that have a timestamp in the time-range (@starttime,@endtime].
// If blockchain is a non-empty string it only returns assets from @blockchain.
func (rdb *RelDB) GetAssetsWithVolByBlockchain(starttime time.Time, endtime time.Time, blockchain string) (assets []dia.AssetVolume, err error) {
var (
query string
rows pgx.Rows
)
query = fmt.Sprintf(`
SELECT * FROM (
SELECT DISTINCT ON (address,blockchain) symbol,name,address,decimals,blockchain,volume
FROM %s
INNER JOIN %s
ON (asset.asset_id = assetvolume.asset_id)
WHERE time_stamp>to_timestamp(%v) and time_stamp<=to_timestamp(%v)`,
assetTable,
assetVolumeTable,
starttime.Unix(),
endtime.Unix(),
)
if blockchain != "" {
query += fmt.Sprintf(" AND asset.blockchain='%s')", blockchain)
} else {
query += (")")
}
query += " sub ORDER BY volume DESC"
rows, err = rdb.postgresClient.Query(context.Background(), query)
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var (
decimals sql.NullInt64
volume float64
)
asset := dia.Asset{}
err = rows.Scan(&asset.Symbol, &asset.Name, &asset.Address, &decimals, &asset.Blockchain, &volume)
if err != nil {
return
}
if decimals.Valid {
asset.Decimals = uint8(decimals.Int64)
}
assetvolume := dia.AssetVolume{Asset: asset, Volume: volume}
assets = append(assets, assetvolume)
}
return
}
// GetSortedAssetSymbols search asstet by symbol
func (rdb *RelDB) GetSortedAssetSymbols(numAssets int64, skip int64, search string) (volumeSortedAssets []dia.AssetVolume, err error) {
var (
queryString string
query string
rows pgx.Rows
)
if numAssets == 0 {
queryString = `
SELECT a.symbol,a.name,a.address,a.decimals,a.blockchain,av.volume
FROM %s
INNER JOIN %s
ON (asset.asset_id = assetvolume.asset_id)
WHERE symbol ILIKE '%s%%'
ORDER BY assetvolume.volume
DESC LIMIT 100`
query = fmt.Sprintf(queryString, assetTable, assetVolumeTable, search)
} else {
queryString = `
SELECT DISTINCT ON (av.volume,av.asset_id) a.symbol,a.name,a.address,a.decimals,a.blockchain,av.volume
FROM %s av
INNER JOIN %s a
ON av.asset_id=a.asset_id
INNER JOIN %s es
ON av.asset_id=es.asset_id INNER JOIN %s e
ON es.exchange=e.name
WHERE e.centralized=true
AND a.symbol ILIKE '%s%%'
ORDER BY av.volume