-
Notifications
You must be signed in to change notification settings - Fork 196
Expand file tree
/
Copy pathcluster.rs
More file actions
1181 lines (1035 loc) · 36.6 KB
/
Copy pathcluster.rs
File metadata and controls
1181 lines (1035 loc) · 36.6 KB
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
use crate::{
clients::{
bens::{
get_address_multichain, get_protocols, lookup_address_multichain,
lookup_domain_name_multichain,
},
blockscout,
},
error::{ParseError, ServiceError},
repository::{
address_token_balances::{self, ListAddressTokensPageToken, ListTokenHoldersPageToken},
addresses, block_ranges, chains, hashes, interop_message_transfers, interop_messages,
tokens::{self, ListClusterTokensPageToken, ListTokenUpdatesPageToken},
},
services::{
self, MIN_QUERY_LENGTH,
cache::ClusterCaches,
chain_metrics,
coin_price::try_fetch_coin_price,
dapp_search,
macros::{maybe_cache_lookup, preload_domain_info},
quick_search::{self, SearchContext, SearchTerm},
},
types::{
ChainId,
address_token_balances::{AggregatedAddressTokenBalance, TokenHolder},
addresses::{AggregatedAddressInfo, ChainAddressInfo},
block_ranges::ChainBlockNumber,
chain_metrics::{ChainMetricKind, ChainMetrics},
chains::Chain,
dapp::MarketplaceDapp,
domains::{Domain, DomainInfo, ProtocolInfo},
hashes::{Hash, HashType},
interop_messages::{ExtendedInteropMessage, MessageDirection},
order_direction::OrderDirection,
portfolio::AddressPortfolio,
search_results::{QuickSearchResult, Redirect},
tokens::{AggregatedToken, TokenListUpdate, TokenType},
},
};
use alloy_primitives::{Address as AddressAlloy, TxHash};
use api_client_framework::HttpApiClient;
use bens_proto::blockscout::bens::v1 as bens_proto;
use itertools::Itertools;
use regex::Regex;
use sea_orm::{
DatabaseConnection,
prelude::{BigDecimal, DateTime},
};
use std::{
cmp::Ordering,
collections::{BTreeMap, HashMap, HashSet},
str::FromStr,
sync::{Arc, OnceLock},
};
pub type BlockscoutClients = Arc<BTreeMap<ChainId, Arc<HttpApiClient>>>;
const BENS_PROTOCOLS_LIMIT: usize = 5;
pub struct Cluster {
db: DatabaseConnection,
name: String,
chain_ids: Vec<ChainId>,
blockscout_clients: BlockscoutClients,
quick_search_chains: Vec<ChainId>,
dapp_client: HttpApiClient,
bens_client: HttpApiClient,
bens_priority_protocols: Vec<String>,
caches: ClusterCaches,
}
impl Cluster {
#[allow(clippy::too_many_arguments)]
pub fn new(
db: DatabaseConnection,
name: String,
chain_ids: Vec<ChainId>,
blockscout_clients: BlockscoutClients,
quick_search_chains: Vec<ChainId>,
dapp_client: HttpApiClient,
bens_client: HttpApiClient,
bens_priority_protocols: Vec<String>,
caches: ClusterCaches,
) -> Self {
Self {
db,
name,
chain_ids,
blockscout_clients,
quick_search_chains,
dapp_client,
bens_client,
bens_priority_protocols,
caches,
}
}
pub fn validate_chain_id(&self, chain_id: ChainId) -> Result<(), ServiceError> {
if !self.chain_ids.contains(&chain_id) {
return Err(ServiceError::InvalidClusterChainId(chain_id));
}
Ok(())
}
pub fn search_context(&self, is_aggregated: bool) -> SearchContext<'_> {
SearchContext {
cluster: self,
db: Arc::new(self.db.clone()),
is_aggregated,
}
}
/// If `chain_ids` is empty, then cluster will include all active chains.
pub async fn active_chain_ids(&self) -> Result<Vec<ChainId>, ServiceError> {
let chain_ids = if self.chain_ids.is_empty() {
services::chains::list_repo_chains_cached(&self.db, true)
.await?
.into_iter()
.map(|c| c.id)
.collect()
} else {
self.chain_ids.clone()
};
Ok(chain_ids)
}
pub async fn validate_and_prepare_chain_ids(
&self,
chain_ids: Vec<ChainId>,
) -> Result<Vec<ChainId>, ServiceError> {
let active_chain_ids = self.active_chain_ids().await?;
let chain_ids = if chain_ids.is_empty() {
active_chain_ids
} else {
let active_chain_ids = active_chain_ids.into_iter().collect::<HashSet<_>>();
let unsupported_chain_ids = chain_ids
.iter()
.filter(|chain_id| !active_chain_ids.contains(chain_id))
.map(|id| id.to_string())
.collect::<Vec<_>>();
if !unsupported_chain_ids.is_empty() {
return Err(ParseError::Custom(format!(
"unsupported chain ids provided: {}",
unsupported_chain_ids.join(", ")
))
.into());
}
chain_ids
};
Ok(chain_ids)
}
pub async fn list_chains(
&self,
sort_metric: Option<ChainMetricKind>,
order_direction: Option<OrderDirection>,
) -> Result<Vec<Chain>, ServiceError> {
let chain_ids = self.active_chain_ids().await?.into_iter().collect();
let mut chains = chains::list_by_ids(&self.db, chain_ids)
.await?
.into_iter()
.map(|c| c.into())
.collect::<Vec<Chain>>();
let metrics = self
.list_chain_metrics(sort_metric, order_direction)
.await?;
let order_map = metrics
.iter()
.enumerate()
.map(|(i, m)| (m.chain_id, i))
.collect::<HashMap<_, _>>();
chains.sort_by_key(|chain| order_map.get(&chain.id).unwrap_or(&usize::MAX));
Ok(chains)
}
pub async fn list_chain_metrics(
&self,
sort_metric: Option<ChainMetricKind>,
order_direction: Option<OrderDirection>,
) -> Result<Vec<ChainMetrics>, ServiceError> {
let chain_ids = self.active_chain_ids().await?;
let key = format!("{}:chain_metrics", self.name);
let blockscout_clients = self.blockscout_clients.clone();
let get = || async move {
Ok::<_, ServiceError>(
chain_metrics::fetch_chain_metrics(&blockscout_clients, &chain_ids).await,
)
};
let mut metrics = maybe_cache_lookup!(self.caches.chain_metrics.as_ref(), key, get)?;
let sort_metric = sort_metric.unwrap_or_default();
let desc = order_direction.unwrap_or_default() == OrderDirection::Desc;
metrics.sort_by(|left, right| {
let ordering = match (
left.metric_value_for_sorting(sort_metric),
right.metric_value_for_sorting(sort_metric),
) {
(Some(l), Some(r)) => {
if desc {
r.total_cmp(&l)
} else {
l.total_cmp(&r)
}
}
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => Ordering::Equal,
};
if ordering == Ordering::Equal {
left.chain_id.cmp(&right.chain_id)
} else {
ordering
}
});
Ok(metrics)
}
pub async fn get_interop_message(
&self,
init_chain_id: ChainId,
nonce: i64,
) -> Result<ExtendedInteropMessage, ServiceError> {
self.validate_chain_id(init_chain_id)?;
let message = interop_messages::get(&self.db, init_chain_id, nonce)
.await?
.ok_or_else(|| {
ServiceError::NotFound(format!(
"interop message: init_chain_id={init_chain_id}, nonce={nonce}"
))
})?;
let decoded_payload = if let (Some(payload), Some(target_address_hash)) =
(&message.payload, &message.target_address_hash)
{
self.fetch_decoded_calldata_cached(
payload,
target_address_hash.to_string(),
init_chain_id,
)
.await
.inspect_err(|e| {
tracing::error!("failed to fetch decoded calldata: {e}");
})
.ok()
} else {
None
};
let extended_message = ExtendedInteropMessage {
message,
decoded_payload,
};
Ok(extended_message)
}
#[allow(clippy::too_many_arguments)]
pub async fn list_interop_messages(
&self,
init_chain_id: Option<ChainId>,
relay_chain_id: Option<ChainId>,
address: Option<AddressAlloy>,
direction: Option<MessageDirection>,
nonce: Option<i64>,
page_size: u64,
page_token: Option<(DateTime, TxHash)>,
) -> Result<(Vec<ExtendedInteropMessage>, Option<(DateTime, TxHash)>), ServiceError> {
if let Some(init_chain_id) = init_chain_id {
self.validate_chain_id(init_chain_id)?;
}
if let Some(relay_chain_id) = relay_chain_id {
self.validate_chain_id(relay_chain_id)?;
}
let cluster_chain_ids = self.active_chain_ids().await?;
let (messages, next_page_token) = interop_messages::list(
&self.db,
init_chain_id,
relay_chain_id,
address,
direction,
nonce,
Some(cluster_chain_ids),
page_size,
page_token,
)
.await?;
let messages = messages
.into_iter()
.map(|m| ExtendedInteropMessage {
message: m,
decoded_payload: None,
})
.collect();
Ok((messages, next_page_token))
}
pub async fn count_interop_messages(&self, chain_id: ChainId) -> Result<u64, ServiceError> {
self.validate_chain_id(chain_id)?;
let cluster_chain_ids = self.active_chain_ids().await?;
let count = interop_messages::count(&self.db, chain_id, Some(cluster_chain_ids)).await?;
Ok(count)
}
pub async fn get_address_info_aggregated(
&self,
address: AddressAlloy,
) -> Result<AggregatedAddressInfo, ServiceError> {
let cluster_chain_ids = self.active_chain_ids().await?;
let mut address_info = addresses::get_aggregated_address_info(
&self.db,
address,
Some(cluster_chain_ids.clone()),
)
.await?
.unwrap_or_else(|| AggregatedAddressInfo::default(address.into()));
let (has_tokens, has_interop_message_transfers, coin_price, domain_info) = futures::join!(
address_token_balances::check_if_tokens_at_address(
&self.db,
address,
cluster_chain_ids.clone()
),
interop_message_transfers::check_if_interop_message_transfers_at_address(
&self.db,
address,
cluster_chain_ids,
),
self.fetch_coin_price_cached(),
self.get_domain_info_cached(address),
);
address_info.has_tokens = has_tokens?;
address_info.has_interop_message_transfers = has_interop_message_transfers?;
address_info.exchange_rate = coin_price
.inspect_err(|e| {
tracing::error!("failed to fetch coin price: {e}");
})
.ok()
.flatten();
address_info.domain_info = domain_info?;
Ok(address_info)
}
pub async fn get_address_portfolio(
&self,
address: AddressAlloy,
chain_ids: Vec<ChainId>,
) -> Result<AddressPortfolio, ServiceError> {
let chain_ids = self.validate_and_prepare_chain_ids(chain_ids).await?;
let chain_values =
address_token_balances::portfolio_by_address(&self.db, address, chain_ids).await?;
let total_value = chain_values
.iter()
.fold(BigDecimal::from(0), |acc, v| acc + v.value.clone());
Ok(AddressPortfolio {
total_value,
chain_values,
})
}
#[allow(clippy::too_many_arguments)]
pub async fn list_address_tokens(
&self,
address: AddressAlloy,
token_types: Vec<TokenType>,
chain_ids: Vec<ChainId>,
query: Option<String>,
page_size: u64,
page_token: Option<ListAddressTokensPageToken>,
filter_poor_reputation: bool,
) -> Result<
(
Vec<AggregatedAddressTokenBalance>,
Option<ListAddressTokensPageToken>,
),
ServiceError,
> {
let chain_ids = self.validate_and_prepare_chain_ids(chain_ids).await?;
let res = address_token_balances::list_by_address(
&self.db,
address,
token_types,
chain_ids,
query,
page_size,
page_token,
filter_poor_reputation,
)
.await?;
Ok(res)
}
pub async fn list_cluster_tokens(
&self,
token_types: Vec<TokenType>,
chain_ids: Vec<ChainId>,
query: Option<String>,
page_size: u64,
page_token: Option<ListClusterTokensPageToken>,
) -> Result<(Vec<AggregatedToken>, Option<ListClusterTokensPageToken>), ServiceError> {
let chain_ids = self.validate_and_prepare_chain_ids(chain_ids).await?;
let res = tokens::list_aggregated_tokens(
&self.db,
vec![],
chain_ids,
token_types,
query,
page_size,
page_token,
)
.await?;
Ok(res)
}
pub async fn get_aggregated_token(
&self,
address: AddressAlloy,
chain_id: ChainId,
) -> Result<Option<AggregatedToken>, ServiceError> {
self.validate_chain_id(chain_id)?;
let token = tokens::get_aggregated_token(&self.db, address, chain_id).await?;
Ok(token)
}
pub async fn list_token_holders(
&self,
address: AddressAlloy,
chain_id: ChainId,
page_size: u64,
page_token: Option<ListTokenHoldersPageToken>,
) -> Result<(Vec<TokenHolder>, Option<ListTokenHoldersPageToken>), ServiceError> {
self.validate_chain_id(chain_id)?;
let holders = address_token_balances::list_token_holders(
&self.db, address, chain_id, page_size, page_token,
)
.await?;
Ok(holders)
}
async fn fetch_decoded_calldata_cached(
&self,
calldata: &alloy_primitives::Bytes,
address_hash: String,
chain_id: ChainId,
) -> Result<serde_json::Value, ServiceError> {
let blockscout_client = self
.blockscout_clients
.get(&chain_id)
.ok_or_else(|| ServiceError::Internal(anyhow::anyhow!("blockscout client not found")))?
.clone();
let calldata_hash = alloy_primitives::keccak256(calldata).to_string();
let calldata = calldata.to_string();
let key = format!("decoded_calldata:{chain_id}:{address_hash}:{calldata_hash}");
let get_decoded_payload = || async move {
blockscout_client
.request(&blockscout::decode_calldata::DecodeCalldata {
params: blockscout::decode_calldata::DecodeCalldataParams {
calldata,
address_hash,
},
})
.await
.map(|r| r.result)
.map_err(ServiceError::from)
};
maybe_cache_lookup!(&self.caches.decoded_calldata, key, get_decoded_payload)
}
pub async fn search_hashes(
&self,
query: String,
hash_type: Option<HashType>,
chain_ids: Vec<ChainId>,
page_size: u64,
page_token: Option<ChainId>,
) -> Result<(Vec<Hash>, Option<ChainId>), ServiceError> {
let hash = match alloy_primitives::B256::from_str(&query) {
Ok(hash) => hash,
Err(_) => return Ok((vec![], None)),
};
let chain_ids = self.validate_and_prepare_chain_ids(chain_ids).await?;
let (blocks, page_token) =
hashes::list(&self.db, hash, hash_type, chain_ids, page_size, page_token).await?;
let hashes = blocks
.into_iter()
.map(Hash::try_from)
.collect::<Result<Vec<_>, _>>()?;
Ok((hashes, page_token))
}
pub async fn search_blocks(
&self,
query: String,
chain_ids: Vec<ChainId>,
page_size: u64,
page_token: Option<ChainId>,
) -> Result<(Vec<Hash>, Option<ChainId>), ServiceError> {
self.search_hashes(
query,
Some(HashType::Block),
chain_ids,
page_size,
page_token,
)
.await
}
pub async fn search_transactions(
&self,
query: String,
chain_ids: Vec<ChainId>,
page_size: u64,
page_token: Option<ChainId>,
) -> Result<(Vec<Hash>, Option<ChainId>), ServiceError> {
self.search_hashes(
query,
Some(HashType::Transaction),
chain_ids,
page_size,
page_token,
)
.await
}
pub async fn search_block_numbers(
&self,
query: String,
chain_ids: Vec<ChainId>,
page_size: u64,
page_token: Option<ChainId>,
) -> Result<(Vec<ChainBlockNumber>, Option<ChainId>), ServiceError> {
let block_number = match alloy_primitives::BlockNumber::from_str(&query) {
Ok(block_number) => block_number,
Err(_) => return Ok((vec![], None)),
};
let chain_ids = self.validate_and_prepare_chain_ids(chain_ids).await?;
let (block_ranges, page_token) = block_ranges::list_matching_block_ranges_paginated(
&self.db,
block_number,
chain_ids,
page_size,
page_token,
)
.await?;
let block_numbers: Vec<_> = block_ranges
.into_iter()
.map(|r| ChainBlockNumber {
chain_id: r.chain_id,
block_number,
})
.collect::<Vec<_>>();
Ok((block_numbers, page_token))
}
pub async fn search_addresses_aggregated(
&self,
query: String,
chain_ids: Vec<ChainId>,
page_size: u64,
page_token: Option<AddressAlloy>,
) -> Result<(Vec<AggregatedAddressInfo>, Option<AddressAlloy>), ServiceError> {
if query.len() < MIN_QUERY_LENGTH {
return Ok((vec![], None));
}
let (addresses, contract_name_query) = self.prepare_addresses_query(query).await?;
let chain_ids = self.validate_and_prepare_chain_ids(chain_ids).await?;
let (mut addresses, page_token) = addresses::list_aggregated_address_infos(
&self.db,
addresses,
Some(chain_ids),
contract_name_query,
page_size,
page_token,
)
.await?;
preload_domain_info!(self, addresses);
Ok((addresses, page_token))
}
pub async fn search_addresses_non_aggregated(
&self,
query: String,
chain_ids: Vec<ChainId>,
page_size: u64,
page_token: Option<(AddressAlloy, ChainId)>,
) -> Result<(Vec<ChainAddressInfo>, Option<(AddressAlloy, ChainId)>), ServiceError> {
if query.len() < MIN_QUERY_LENGTH {
return Ok((vec![], None));
}
let (addresses, contract_name_query) = self.prepare_addresses_query(query).await?;
let chain_ids = self.validate_and_prepare_chain_ids(chain_ids).await?;
let (mut addresses, page_token) = addresses::list_chain_address_infos(
&self.db,
addresses,
Some(chain_ids),
contract_name_query,
page_size,
page_token,
)
.await?;
preload_domain_info!(self, addresses);
Ok((addresses, page_token))
}
async fn prepare_addresses_query(
&self,
query: String,
) -> Result<(Vec<AddressAlloy>, Option<String>), ServiceError> {
let (addresses, contract_name_query) = {
// 1. If query is an address then use it directly
// 2. If query matches an explicit domain name with TLD (e.g. "name.eth") then
// lookup the domain name and return the addresses associated with it
// 3. Otherwise, fallback to a contract name search
// TODO: support joint paginated search for domain names without TLD and contract names;
// we need to first handle all pages for domains and then switch to contract names
if let Some(address) = SearchTerm::try_parse_address(&query) {
(vec![address], None)
} else if domain_name_with_tld_regex().is_match(&query) {
let domains = self
.search_domains_cached(query.clone(), vec![], 1, None)
.await
.map(|(d, _)| d)
.inspect_err(|err| {
tracing::error!(
err = ?err,
"failed to lookup domains"
);
})
.unwrap_or_default();
let addresses = domains
.iter()
.filter_map(|d| d.address)
.collect::<HashSet<_>>()
.into_iter()
.collect::<Vec<_>>();
if addresses.is_empty() {
(vec![], Some(query.to_string()))
} else {
(addresses, None)
}
} else {
(vec![], Some(query.to_string()))
}
};
Ok((addresses, contract_name_query))
}
pub async fn search_nfts_cached(
&self,
query: String,
chain_ids: Vec<ChainId>,
page_size: u64,
page_token: Option<ListClusterTokensPageToken>,
) -> Result<(Vec<AggregatedToken>, Option<ListClusterTokensPageToken>), ServiceError> {
self.search_tokens_cached(
query,
chain_ids,
vec![TokenType::Erc721, TokenType::Erc1155],
page_size,
page_token,
)
.await
}
pub async fn search_token_infos_cached(
&self,
query: String,
chain_ids: Vec<ChainId>,
page_size: u64,
page_token: Option<ListClusterTokensPageToken>,
) -> Result<(Vec<AggregatedToken>, Option<ListClusterTokensPageToken>), ServiceError> {
self.search_tokens_cached(
query,
chain_ids,
vec![TokenType::Erc20],
page_size,
page_token,
)
.await
}
pub async fn search_tokens_cached(
&self,
query: String,
chain_ids: Vec<ChainId>,
token_types: Vec<TokenType>,
page_size: u64,
page_token: Option<ListClusterTokensPageToken>,
) -> Result<(Vec<AggregatedToken>, Option<ListClusterTokensPageToken>), ServiceError> {
if query.len() < MIN_QUERY_LENGTH {
return Ok((vec![], None));
}
let (addresses, tokens_query) =
if let Ok(address) = alloy_primitives::Address::from_str(&query) {
(vec![address], None)
} else {
(vec![], Some(query.to_string()))
};
let is_first_page = page_token.is_none();
let key = {
let chain_ids_key = chain_ids
.iter()
.map(|c| c.to_string())
.collect::<Vec<_>>()
.join(",");
let token_types_key = token_types
.iter()
.map(|t| format!("{:?}", t))
.collect::<Vec<_>>()
.join(",");
format!(
"{}:{}:{}:{}:{}",
self.name, query, chain_ids_key, token_types_key, page_size
)
};
let chain_ids = self.validate_and_prepare_chain_ids(chain_ids).await?;
let db = self.db.clone();
let get = || async move {
tokens::list_aggregated_tokens(
&db,
addresses,
chain_ids,
token_types,
tokens_query,
page_size,
page_token,
)
.await
.map_err(ServiceError::from)
};
// cache only the first page to speed up quick search
let (mut tokens, page_token) = if is_first_page {
maybe_cache_lookup!(self.caches.token_search.as_ref(), key, get)?
} else {
get().await?
};
tokens.iter_mut().for_each(|token| {
if let Some(icon_url) = &mut token.icon_url {
*icon_url = replace_coingecko_logo_uri_to_large(icon_url);
}
});
Ok((tokens, page_token))
}
pub async fn fetch_coin_price_cached(&self) -> Result<Option<String>, ServiceError> {
let chain_ids = self.chain_ids.clone();
let blockscout_clients = Arc::clone(&self.blockscout_clients);
let key = format!("{}:coin_price", self.name);
let get = || async {
Ok::<_, ServiceError>(try_fetch_coin_price(blockscout_clients, chain_ids).await)
};
let coin_price = maybe_cache_lookup!(self.caches.coin_price.as_ref(), key, get)?;
Ok(coin_price)
}
pub async fn search_domains_cached(
&self,
query: String,
_chain_ids: Vec<ChainId>, // NOTE: required for backward compatibility
page_size: u64,
page_token: Option<String>,
) -> Result<(Vec<Domain>, Option<String>), ServiceError> {
let protocols = self.prepare_protocol_ids().await?;
let key = format!(
"{}:{}:{}:{}",
query,
protocols.clone().unwrap_or_default(),
page_size,
page_token.clone().unwrap_or_default(),
);
let bens_client = self.bens_client.clone();
let get = || search_domains(bens_client, query, protocols.clone(), page_size, page_token);
let (domains, next_page_token) =
maybe_cache_lookup!(self.caches.domain_search.as_ref(), key, get)?;
Ok((domains, next_page_token))
}
// TODO: Add working pagination for dapps
// Currently this method is just for compatibility with paginated_list_by_query_endpoint! macro
pub async fn search_dapps_paginated(
&self,
query: String,
chain_ids: Vec<ChainId>,
_page_size: u64,
_page_token: Option<String>,
) -> Result<(Vec<MarketplaceDapp>, Option<String>), ServiceError> {
let chain_ids = self.validate_and_prepare_chain_ids(chain_ids).await?;
let dapps = self.search_dapps(Some(query), chain_ids, None).await?;
Ok((dapps, None))
}
pub async fn search_dapps(
&self,
query: Option<String>,
chain_ids: Vec<ChainId>,
categories: Option<String>,
) -> Result<Vec<MarketplaceDapp>, ServiceError> {
let chain_ids = self.validate_and_prepare_chain_ids(chain_ids).await?;
dapp_search::search_dapps(
&self.dapp_client,
query,
categories,
chain_ids,
&self.caches.marketplace_enabled,
)
.await
}
pub async fn get_domain_info_cached(
&self,
address: alloy_primitives::Address,
) -> Result<Option<DomainInfo>, ServiceError> {
let protocols = self.prepare_protocol_ids().await?;
let key = format!("{}:{}", self.name, address);
let bens_client = self.bens_client.clone();
let get = || get_domain_info(bens_client, address, protocols.clone());
let domain_info = maybe_cache_lookup!(self.caches.domain_info.as_ref(), key, get)?;
Ok(domain_info)
}
pub async fn get_domain_info_batch_cached(
&self,
addresses: impl IntoIterator<Item = alloy_primitives::Address>,
) -> HashMap<alloy_primitives::Address, DomainInfo> {
let jobs = addresses.into_iter().map(|address| async move {
let domain_info = self.get_domain_info_cached(address).await.ok()??;
Some((address, domain_info))
});
futures::future::join_all(jobs)
.await
.into_iter()
.flatten()
.collect()
}
pub async fn get_protocols_cached(&self) -> Result<Vec<ProtocolInfo>, ServiceError> {
let key = format!("{}:domain_protocols", self.name);
let bens_client = self.bens_client.clone();
let chain_ids = self.chain_ids.clone();
let priority_protocols = self.bens_priority_protocols.clone();
let get = || get_protocols(bens_client, chain_ids, priority_protocols);
let protocols = maybe_cache_lookup!(self.caches.domain_protocols.as_ref(), key, get)?;
Ok(protocols)
}
/// Returns comma-separated protocol IDs for use in BENS multichain endpoints
async fn prepare_protocol_ids(&self) -> Result<Option<String>, ServiceError> {
let protocols = self.get_protocols_cached().await?;
if protocols.is_empty() {
Ok(None)
} else {
Ok(Some(
protocols
.iter()
.map(|p| p.id.as_str())
.take(BENS_PROTOCOLS_LIMIT)
.collect::<Vec<_>>()
.join(","),
))
}
}
pub async fn quick_search(
&self,
query: String,
is_aggregated: bool,
unlimited_per_chain: bool,
) -> Result<QuickSearchResult, ServiceError> {
let context = self.search_context(is_aggregated);
let result = quick_search::quick_search(
query,
&self.quick_search_chains,
&context,
unlimited_per_chain,
)
.await?;
Ok(result)
}
pub async fn check_redirect(&self, query: &str) -> Result<Option<Redirect>, ServiceError> {
let context = self.search_context(false);
let result = quick_search::check_redirect(query, &context).await?;
Ok(result)
}
pub async fn list_token_updates(
&self,
chain_ids: Vec<ChainId>,
page_size: u64,
page_token: Option<ListTokenUpdatesPageToken>,
) -> Result<(Vec<TokenListUpdate>, Option<ListTokenUpdatesPageToken>), ServiceError> {
let chain_ids = self.validate_and_prepare_chain_ids(chain_ids).await?;
let (updates, next_page_token) =
tokens::list_token_updates(&self.db, chain_ids, page_size, page_token).await?;
Ok((updates, next_page_token))
}
pub async fn lookup_address_domains(
&self,
address: String,
page_size: u32,
page_token: Option<String>,
) -> Result<(Vec<Domain>, Option<String>), ServiceError> {
let protocols = self.prepare_protocol_ids().await?;
lookup_address_domains(
self.bens_client.clone(),
address,
protocols,
page_size,
page_token,
)
.await
}
}
async fn get_domain_info(
bens_client: HttpApiClient,
address: alloy_primitives::Address,
protocols: Option<String>,
) -> Result<Option<DomainInfo>, ServiceError> {
let request = bens_proto::GetAddressMultichainRequest {
address: address.to_string(),
chain_id: None,
protocols,
};
let res = bens_client
.request(&get_address_multichain::GetAddressMultichain { request })