tail-fin-arkham 0.7.8

Arkham Intel adapter for tail-fin: pure-HTTP client for api.arkm.com (chain analytics, address profiles, entity search, transfers)
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
//! HTTP client for `api.arkm.com`.
//!
//! Pure wreq — no browser, no cookies. See `signing` for the X-Payload
//! algorithm and the module-level docs in `lib.rs` for context.
//!
//! Most endpoints return `serde_json::Value` because Arkham's full schema
//! catalogue (101 schemas across 84 paths, with deeply nested oneOfs and
//! example-only fields) is impractical to type by hand. The three highest-
//! value endpoints (`search`, `address_enriched`, `transfers`) are typed
//! into named structs in `types.rs`. Library users who want types for the
//! rest can `serde_json::from_value` into their own structs.

use serde_json::Value;
use std::time::{SystemTime, UNIX_EPOCH};
use tail_fin_common::TailFinError;
use wreq::header::{HeaderMap, HeaderValue, ACCEPT, ORIGIN, REFERER};

use crate::parsing::{parse_address_enriched, parse_search_results, parse_transfers};
use crate::signing::sign_payload;
use crate::types::{AddressEnriched, SearchResults, TransfersPage, TransfersQuery};

const API_BASE: &str = "https://api.arkm.com";
const ORIGIN_HEADER: &str = "https://intel.arkm.com";
const REFERER_HEADER: &str = "https://intel.arkm.com/";

/// Default opt-ins for `intelligence/address_enriched/*` endpoints — the
/// SPA always sends these three with `true` and reducing them dilutes the
/// response, so we default the same way.
const ADDRESS_ENRICHED_INCLUDES: &[(&str, &str)] = &[
    ("includeTags", "true"),
    ("includeEntityPredictions", "true"),
    ("includeClusters", "true"),
];

/// HTTP client for Arkham Intel's public data API.
pub struct ArkhamClient {
    client: wreq::Client,
}

// `clippy::too_many_arguments` flags several methods (counterparties_*,
// swaps, token_top, intelligence_entity_balance_changes) that mirror the
// upstream OpenAPI surface 1:1. Splitting those into builder structs would
// add a layer that doesn't earn its keep on a v0 spike — keep the call
// sites flat and let callers pass `None` for unused filters.
#[allow(clippy::too_many_arguments)]
impl ArkhamClient {
    /// Build a Chrome-145-emulated client. The TLS fingerprint is overkill
    /// for `api.arkm.com` (vanilla curl works), but keeps us aligned with the
    /// SPA and inoculates against future Cloudflare tightening.
    pub fn new() -> Result<Self, TailFinError> {
        let emu = wreq_util::EmulationOption::builder()
            .emulation(wreq_util::Emulation::Chrome145)
            .emulation_os(wreq_util::EmulationOS::MacOS)
            .build();
        let client = wreq::Client::builder()
            .emulation(emu)
            .connect_timeout(std::time::Duration::from_secs(10))
            .timeout(std::time::Duration::from_secs(30))
            .build()
            .map_err(|e| TailFinError::Api(format!("failed to build HTTP client: {e}")))?;
        Ok(Self { client })
    }

    // ─── building block ──────────────────────────────────────────────────
    //
    // Every public endpoint goes through `signed_get`. `path` is the URL
    // pathname (used for both the URL and the X-Payload signature — they
    // MUST match, query string is excluded from signing per the SPA's
    // `new URL(t).pathname` extraction). `query_pairs` becomes the URL's
    // `?key=val&key=val`. Multi-value params (e.g. `base=` repeated) pass
    // multiple pairs with the same key.

    /// Call any signed GET endpoint and return the response body as `Value`.
    /// Public so library users can hit endpoints we haven't typed yet.
    pub async fn signed_get(
        &self,
        path: &str,
        query_pairs: &[(&str, &str)],
    ) -> Result<Value, TailFinError> {
        let url = if query_pairs.is_empty() {
            format!("{API_BASE}{path}")
        } else {
            let qs = query_pairs
                .iter()
                .map(|(k, v)| format!("{}={}", urlencoding::encode(k), urlencoding::encode(v)))
                .collect::<Vec<_>>()
                .join("&");
            format!("{API_BASE}{path}?{qs}")
        };
        self.send_signed(&url, path).await
    }

    async fn send_signed(&self, url: &str, path: &str) -> Result<Value, TailFinError> {
        let ts = current_unix_seconds()?;
        let payload = sign_payload(path, &ts);
        let headers = build_signed_headers(&ts, &payload)?;

        let resp = self
            .client
            .get(url)
            .headers(headers)
            .send()
            .await
            .map_err(|e| TailFinError::Api(format!("Arkham GET {path} failed: {e}")))?;

        let status = resp.status();
        let body_bytes = resp
            .bytes()
            .await
            .map_err(|e| TailFinError::Api(format!("Arkham GET {path} body read failed: {e}")))?;

        if !status.is_success() {
            let preview = String::from_utf8_lossy(&body_bytes);
            return Err(TailFinError::Api(format!(
                "Arkham GET {path} HTTP {}: {}",
                status.as_u16(),
                preview.chars().take(300).collect::<String>()
            )));
        }

        serde_json::from_slice::<Value>(&body_bytes)
            .map_err(|e| TailFinError::Api(format!("Arkham GET {path} returned non-JSON: {e}")))
    }

    // ─── typed: search / address_enriched / transfers ─────────────────────

    /// Search across entities, tokens, and pools.
    pub async fn search(&self, query: &str) -> Result<SearchResults, TailFinError> {
        let body = self
            .signed_get("/intelligence/search", &[("query", query)])
            .await?;
        parse_search_results(&body)
    }

    /// Cross-chain enriched profile for an EVM-style address.
    pub async fn address_enriched(&self, address: &str) -> Result<AddressEnriched, TailFinError> {
        let path = format!("/intelligence/address_enriched/{address}/all");
        let body = self.signed_get(&path, ADDRESS_ENRICHED_INCLUDES).await?;
        parse_address_enriched(&body)
    }

    /// Page of transfers matching the filter. Pass [`TransfersQuery::default`]
    /// for a default scan, or populate fields like `base`, `flow`, `usd_gte`,
    /// `sort_key`/`sort_dir`, `limit`, `offset` to filter and paginate.
    pub async fn transfers(&self, q: &TransfersQuery<'_>) -> Result<TransfersPage, TailFinError> {
        let pairs = transfers_query_pairs(q);
        let pair_refs: Vec<(&str, &str)> = pairs.iter().map(|(k, v)| (*k, v.as_str())).collect();
        let body = self.signed_get("/transfers", &pair_refs).await?;
        parse_transfers(&body)
    }

    // ─── address-keyed mirrors ───────────────────────────────────────────

    pub async fn balances_address(
        &self,
        address: &str,
        chains: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/balances/address/{address}");
        self.signed_get(&path, &chains_pairs(chains)).await
    }

    pub async fn counterparties_address(
        &self,
        address: &str,
        chains: Option<&str>,
        flow: Option<&str>,
        time_last: Option<&str>,
        usd_gte: Option<&str>,
        limit: Option<u32>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/counterparties/address/{address}");
        let mut q = QueryBuf::new();
        q.push_opt("chains", chains);
        q.push_opt("flow", flow);
        q.push_opt("timeLast", time_last);
        q.push_opt("usdGte", usd_gte);
        q.push_opt_num("limit", limit);
        self.signed_get(&path, &q.as_pairs()).await
    }

    pub async fn flow_address(
        &self,
        address: &str,
        chains: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/flow/address/{address}");
        self.signed_get(&path, &chains_pairs(chains)).await
    }

    pub async fn history_address(
        &self,
        address: &str,
        chains: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/history/address/{address}");
        self.signed_get(&path, &chains_pairs(chains)).await
    }

    /// Single-chain `/intelligence/address/{address}` (NOT the `/all` variant).
    pub async fn intelligence_address(
        &self,
        address: &str,
        chain: &str,
    ) -> Result<Value, TailFinError> {
        let path = format!("/intelligence/address/{address}");
        self.signed_get(&path, &[("chain", chain)]).await
    }

    /// All-chain `/intelligence/address/{address}/all`.
    pub async fn intelligence_address_all(&self, address: &str) -> Result<Value, TailFinError> {
        let path = format!("/intelligence/address/{address}/all");
        self.signed_get(&path, &[]).await
    }

    /// Single-chain enriched profile (vs `address_enriched()` which is `/all`).
    pub async fn intelligence_address_enriched_chain(
        &self,
        address: &str,
        chain: &str,
    ) -> Result<Value, TailFinError> {
        let path = format!("/intelligence/address_enriched/{address}");
        let mut pairs = vec![("chain", chain)];
        pairs.extend_from_slice(ADDRESS_ENRICHED_INCLUDES);
        self.signed_get(&path, &pairs).await
    }

    pub async fn intelligence_contract(
        &self,
        chain: &str,
        address: &str,
    ) -> Result<Value, TailFinError> {
        let path = format!("/intelligence/contract/{chain}/{address}");
        self.signed_get(&path, &[]).await
    }

    pub async fn loans_address(
        &self,
        address: &str,
        chains: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/loans/address/{address}");
        self.signed_get(&path, &chains_pairs(chains)).await
    }

    /// Server REQUIRES `time` (unix milliseconds string). Returns 400
    /// "invalid unix millisecond time" without it.
    pub async fn portfolio_address(
        &self,
        address: &str,
        time: &str,
        chains: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/portfolio/address/{address}");
        let mut q = QueryBuf::new();
        q.push("time", time);
        q.push_opt("chains", chains);
        self.signed_get(&path, &q.as_pairs()).await
    }

    /// Server REQUIRES `pricing_id`. Returns 400 "missing pricingId" without it.
    pub async fn portfolio_timeseries_address(
        &self,
        address: &str,
        pricing_id: &str,
        chains: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/portfolio/timeSeries/address/{address}");
        let mut q = QueryBuf::new();
        q.push("pricingId", pricing_id);
        q.push_opt("chains", chains);
        self.signed_get(&path, &q.as_pairs()).await
    }

    pub async fn volume_address(
        &self,
        address: &str,
        chains: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/volume/address/{address}");
        self.signed_get(&path, &chains_pairs(chains)).await
    }

    // ─── entity-keyed mirrors ────────────────────────────────────────────

    pub async fn balances_entity(
        &self,
        entity: &str,
        chains: Option<&str>,
        cheap: Option<bool>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/balances/entity/{entity}");
        let mut q = QueryBuf::new();
        q.push_opt("chains", chains);
        q.push_opt_bool("cheap", cheap);
        self.signed_get(&path, &q.as_pairs()).await
    }

    pub async fn counterparties_entity(
        &self,
        entity: &str,
        chains: Option<&str>,
        flow: Option<&str>,
        time_last: Option<&str>,
        usd_gte: Option<&str>,
        limit: Option<u32>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/counterparties/entity/{entity}");
        let mut q = QueryBuf::new();
        q.push_opt("chains", chains);
        q.push_opt("flow", flow);
        q.push_opt("timeLast", time_last);
        q.push_opt("usdGte", usd_gte);
        q.push_opt_num("limit", limit);
        self.signed_get(&path, &q.as_pairs()).await
    }

    pub async fn flow_entity(
        &self,
        entity: &str,
        chains: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/flow/entity/{entity}");
        self.signed_get(&path, &chains_pairs(chains)).await
    }

    pub async fn history_entity(
        &self,
        entity: &str,
        chains: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/history/entity/{entity}");
        self.signed_get(&path, &chains_pairs(chains)).await
    }

    pub async fn loans_entity(
        &self,
        entity: &str,
        chains: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/loans/entity/{entity}");
        self.signed_get(&path, &chains_pairs(chains)).await
    }

    /// Server REQUIRES `time` (unix milliseconds string). Returns 400
    /// "invalid unix millisecond time" without it.
    pub async fn portfolio_entity(
        &self,
        entity: &str,
        time: &str,
        chains: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/portfolio/entity/{entity}");
        let mut q = QueryBuf::new();
        q.push("time", time);
        q.push_opt("chains", chains);
        self.signed_get(&path, &q.as_pairs()).await
    }

    /// Server REQUIRES `pricing_id`. Returns 400 "missing pricingId" without it.
    pub async fn portfolio_timeseries_entity(
        &self,
        entity: &str,
        pricing_id: &str,
        chains: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/portfolio/timeSeries/entity/{entity}");
        let mut q = QueryBuf::new();
        q.push("pricingId", pricing_id);
        q.push_opt("chains", chains);
        self.signed_get(&path, &q.as_pairs()).await
    }

    pub async fn volume_entity(
        &self,
        entity: &str,
        chains: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/volume/entity/{entity}");
        self.signed_get(&path, &chains_pairs(chains)).await
    }

    pub async fn intelligence_entity(&self, entity: &str) -> Result<Value, TailFinError> {
        let path = format!("/intelligence/entity/{entity}");
        self.signed_get(&path, &[]).await
    }

    pub async fn intelligence_entity_summary(&self, entity: &str) -> Result<Value, TailFinError> {
        let path = format!("/intelligence/entity/{entity}/summary");
        self.signed_get(&path, &[]).await
    }

    pub async fn intelligence_entity_predictions(
        &self,
        entity: &str,
    ) -> Result<Value, TailFinError> {
        let path = format!("/intelligence/entity_predictions/{entity}");
        self.signed_get(&path, &[]).await
    }

    /// Recent balance changes across entities. Server REQUIRES four params
    /// — `order_by`, `order_dir`, `interval`, and `limit`. Without `interval`
    /// the server returns 400; without `limit` it returns 500. Valid
    /// `order_by`: `balanceUsd | balanceUsdChange | balanceUsdPctChange |
    /// balanceUnit | balanceUnitChange | balanceUnitPctChange`. Valid
    /// `interval`: `7d | 14d | 30d`.
    pub async fn intelligence_entity_balance_changes(
        &self,
        order_by: &str,
        order_dir: &str,
        interval: &str,
        limit: u32,
        chains: Option<&str>,
        entity_types: Option<&str>,
        entity_ids: Option<&str>,
        offset: Option<u32>,
    ) -> Result<Value, TailFinError> {
        let mut q = QueryBuf::new();
        q.push("orderBy", order_by);
        q.push("orderDir", order_dir);
        q.push("interval", interval);
        q.push_opt_num("limit", Some(limit));
        q.push_opt("chains", chains);
        q.push_opt("entityTypes", entity_types);
        q.push_opt("entityIds", entity_ids);
        q.push_opt_num("offset", offset);
        self.signed_get("/intelligence/entity_balance_changes", &q.as_pairs())
            .await
    }

    pub async fn intelligence_entity_types(&self) -> Result<Value, TailFinError> {
        self.signed_get("/intelligence/entity_types", &[]).await
    }

    // ─── token endpoints ─────────────────────────────────────────────────

    pub async fn token_addresses(&self, id: &str) -> Result<Value, TailFinError> {
        let path = format!("/token/addresses/{id}");
        self.signed_get(&path, &[]).await
    }

    pub async fn token_balance_by_addr(
        &self,
        chain: &str,
        token_address: &str,
        entity_id: Option<&str>,
        holder_address: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/token/balance/{chain}/{token_address}");
        let mut q = QueryBuf::new();
        q.push_opt("entityID", entity_id);
        q.push_opt("address", holder_address);
        self.signed_get(&path, &q.as_pairs()).await
    }

    pub async fn token_balance_by_id(
        &self,
        id: &str,
        entity_id: Option<&str>,
        holder_address: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/token/balance/{id}");
        let mut q = QueryBuf::new();
        q.push_opt("entityID", entity_id);
        q.push_opt("address", holder_address);
        self.signed_get(&path, &q.as_pairs()).await
    }

    pub async fn token_holders_by_addr(
        &self,
        chain: &str,
        token_address: &str,
        group_by_entity: Option<bool>,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/token/holders/{chain}/{token_address}");
        let mut q = QueryBuf::new();
        q.push_opt_bool("groupByEntity", group_by_entity);
        q.push_opt_num("limit", limit);
        q.push_opt_num("offset", offset);
        self.signed_get(&path, &q.as_pairs()).await
    }

    pub async fn token_holders_by_id(
        &self,
        id: &str,
        group_by_entity: Option<bool>,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/token/holders/{id}");
        let mut q = QueryBuf::new();
        q.push_opt_bool("groupByEntity", group_by_entity);
        q.push_opt_num("limit", limit);
        q.push_opt_num("offset", offset);
        self.signed_get(&path, &q.as_pairs()).await
    }

    pub async fn token_market(&self, id: &str) -> Result<Value, TailFinError> {
        let path = format!("/token/market/{id}");
        self.signed_get(&path, &[]).await
    }

    pub async fn token_price_history_by_addr(
        &self,
        chain: &str,
        token_address: &str,
        daily: Option<bool>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/token/price/history/{chain}/{token_address}");
        let mut q = QueryBuf::new();
        q.push_opt_bool("daily", daily);
        self.signed_get(&path, &q.as_pairs()).await
    }

    pub async fn token_price_history_by_id(
        &self,
        id: &str,
        daily: Option<bool>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/token/price/history/{id}");
        let mut q = QueryBuf::new();
        q.push_opt_bool("daily", daily);
        self.signed_get(&path, &q.as_pairs()).await
    }

    /// Server REQUIRES `past_time` as an **RFC 3339 timestamp** (e.g.
    /// `2025-12-01T00:00:00Z`) — NOT a Go duration. Server returns 400
    /// "missing pastTime query param" without it, "invalid pastTime format"
    /// with anything that doesn't parse as RFC 3339.
    pub async fn token_price_change(
        &self,
        id: &str,
        past_time: &str,
    ) -> Result<Value, TailFinError> {
        let path = format!("/token/price_change/{id}");
        let mut q = QueryBuf::new();
        q.push("pastTime", past_time);
        self.signed_get(&path, &q.as_pairs()).await
    }

    /// Top tokens. Server REQUIRES four params — `timeframe`,
    /// `order_by_agg`, `order_by_percent`, `from`, `order_by_desc`, AND
    /// `size` — six required params total. Server returns 400 naming
    /// whichever is missing. `from` is the pagination start (0 for the
    /// first page). Note `order_by_agg` here is distinct from the
    /// `order_by` param on `/intelligence/entity_balance_changes`.
    pub async fn token_top(
        &self,
        timeframe: &str,
        order_by_agg: &str,
        order_by_percent: bool,
        order_by_desc: bool,
        from: u32,
        size: u32,
        chains: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let mut q = QueryBuf::new();
        q.push("timeframe", timeframe);
        q.push("orderByAgg", order_by_agg);
        q.push(
            "orderByPercent",
            if order_by_percent { "true" } else { "false" },
        );
        q.push("orderByDesc", if order_by_desc { "true" } else { "false" });
        q.push_opt_num("from", Some(from));
        q.push_opt_num("size", Some(size));
        q.push_opt("chains", chains);
        self.signed_get("/token/top", &q.as_pairs()).await
    }

    /// Server REQUIRES `time_last` (Go duration: `1h`, `24h`, `7d`, `30d`).
    /// Returns 400 "invalid timeLast" without it.
    pub async fn token_top_flow_by_addr(
        &self,
        chain: &str,
        token_address: &str,
        time_last: &str,
        chains: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/token/top_flow/{chain}/{token_address}");
        let mut q = QueryBuf::new();
        q.push("timeLast", time_last);
        q.push_opt("chains", chains);
        self.signed_get(&path, &q.as_pairs()).await
    }

    /// Server REQUIRES `time_last`. See [`token_top_flow_by_addr`].
    pub async fn token_top_flow_by_id(
        &self,
        id: &str,
        time_last: &str,
        chains: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/token/top_flow/{id}");
        let mut q = QueryBuf::new();
        q.push("timeLast", time_last);
        q.push_opt("chains", chains);
        self.signed_get(&path, &q.as_pairs()).await
    }

    pub async fn token_trending(&self) -> Result<Value, TailFinError> {
        self.signed_get("/token/trending", &[]).await
    }

    pub async fn token_trending_by_id(&self, id: &str) -> Result<Value, TailFinError> {
        let path = format!("/token/trending/{id}");
        self.signed_get(&path, &[]).await
    }

    /// Server REQUIRES `granularity` as a Go duration string (`1h`, `1d`,
    /// `30m`, etc. — NOT keywords like `hourly`/`daily`). Returns 400
    /// "missing granularity" or "invalid duration" otherwise. `time_last`
    /// is also de-facto required by the server.
    pub async fn token_volume_by_addr(
        &self,
        chain: &str,
        token_address: &str,
        time_last: &str,
        granularity: &str,
    ) -> Result<Value, TailFinError> {
        let path = format!("/token/volume/{chain}/{token_address}");
        let mut q = QueryBuf::new();
        q.push("timeLast", time_last);
        q.push("granularity", granularity);
        self.signed_get(&path, &q.as_pairs()).await
    }

    /// Server REQUIRES `granularity` and `time_last`. See [`token_volume_by_addr`].
    pub async fn token_volume_by_id(
        &self,
        id: &str,
        time_last: &str,
        granularity: &str,
    ) -> Result<Value, TailFinError> {
        let path = format!("/token/volume/{id}");
        let mut q = QueryBuf::new();
        q.push("timeLast", time_last);
        q.push("granularity", granularity);
        self.signed_get(&path, &q.as_pairs()).await
    }

    pub async fn token_arkham_exchange_tokens(&self) -> Result<Value, TailFinError> {
        self.signed_get("/token/arkham_exchange_tokens", &[]).await
    }

    pub async fn intelligence_token_by_addr(
        &self,
        chain: &str,
        address: &str,
    ) -> Result<Value, TailFinError> {
        let path = format!("/intelligence/token/{chain}/{address}");
        self.signed_get(&path, &[]).await
    }

    pub async fn intelligence_token_by_id(&self, id: &str) -> Result<Value, TailFinError> {
        let path = format!("/intelligence/token/{id}");
        self.signed_get(&path, &[]).await
    }

    // ─── updates feeds ───────────────────────────────────────────────────

    pub async fn intelligence_addresses_updates(
        &self,
        since: Option<&str>,
        limit: Option<u32>,
        page_token: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let mut q = QueryBuf::new();
        q.push_opt("since", since);
        q.push_opt_num("limit", limit);
        q.push_opt("pageToken", page_token);
        self.signed_get("/intelligence/addresses/updates", &q.as_pairs())
            .await
    }

    pub async fn intelligence_entities_updates(
        &self,
        since: Option<&str>,
        limit: Option<u32>,
        page_token: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let mut q = QueryBuf::new();
        q.push_opt("since", since);
        q.push_opt_num("limit", limit);
        q.push_opt("pageToken", page_token);
        self.signed_get("/intelligence/entities/updates", &q.as_pairs())
            .await
    }

    pub async fn intelligence_tags_updates(
        &self,
        since: Option<&str>,
        limit: Option<u32>,
        page_token: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let mut q = QueryBuf::new();
        q.push_opt("since", since);
        q.push_opt_num("limit", limit);
        q.push_opt("pageToken", page_token);
        self.signed_get("/intelligence/tags/updates", &q.as_pairs())
            .await
    }

    pub async fn intelligence_address_tags_updates(
        &self,
        since: Option<&str>,
        limit: Option<u32>,
        page_token: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let mut q = QueryBuf::new();
        q.push_opt("since", since);
        q.push_opt_num("limit", limit);
        q.push_opt("pageToken", page_token);
        self.signed_get("/intelligence/address_tags/updates", &q.as_pairs())
            .await
    }

    // ─── transfers extras + tx ───────────────────────────────────────────

    pub async fn transfers_histogram(
        &self,
        q: &TransfersQuery<'_>,
        granularity: Option<&str>,
    ) -> Result<Value, TailFinError> {
        let mut pairs = transfers_query_pairs(q);
        if let Some(g) = granularity {
            pairs.push(("granularity", g.to_string()));
        }
        let pair_refs: Vec<(&str, &str)> = pairs.iter().map(|(k, v)| (*k, v.as_str())).collect();
        self.signed_get("/transfers/histogram", &pair_refs).await
    }

    pub async fn transfers_histogram_simple(
        &self,
        q: &TransfersQuery<'_>,
    ) -> Result<Value, TailFinError> {
        let pairs = transfers_query_pairs(q);
        let pair_refs: Vec<(&str, &str)> = pairs.iter().map(|(k, v)| (*k, v.as_str())).collect();
        self.signed_get("/transfers/histogram/simple", &pair_refs)
            .await
    }

    /// Server REQUIRES `chain`. Returns 400 "could not parse chain" without it.
    pub async fn transfers_tx(
        &self,
        hash: &str,
        transfer_type: &str,
        chain: &str,
    ) -> Result<Value, TailFinError> {
        let path = format!("/transfers/tx/{hash}");
        let mut q = QueryBuf::new();
        q.push("transferType", transfer_type);
        q.push("chain", chain);
        self.signed_get(&path, &q.as_pairs()).await
    }

    pub async fn tx(&self, hash: &str) -> Result<Value, TailFinError> {
        let path = format!("/tx/{hash}");
        self.signed_get(&path, &[]).await
    }

    /// `base` mirrors `/transfers` (repeated `?base=A&base=B` for multi).
    pub async fn swaps(
        &self,
        base: Option<&[&str]>,
        chains: Option<&str>,
        flow: Option<&str>,
        time_last: Option<&str>,
        usd_gte: Option<&str>,
        sort_key: Option<&str>,
        sort_dir: Option<&str>,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> Result<Value, TailFinError> {
        let mut q = QueryBuf::new();
        if let Some(bs) = base {
            for b in bs {
                q.push("base", b);
            }
        }
        q.push_opt("chains", chains);
        q.push_opt("flow", flow);
        q.push_opt("timeLast", time_last);
        q.push_opt("usdGte", usd_gte);
        q.push_opt("sortKey", sort_key);
        q.push_opt("sortDir", sort_dir);
        q.push_opt_num("limit", limit);
        q.push_opt_num("offset", offset);
        self.signed_get("/swaps", &q.as_pairs()).await
    }

    // ─── cluster + tag + solana subaccounts ──────────────────────────────

    pub async fn cluster_summary(&self, id: &str) -> Result<Value, TailFinError> {
        let path = format!("/cluster/{id}/summary");
        self.signed_get(&path, &[]).await
    }

    pub async fn tag_params(
        &self,
        id: &str,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/tag/{id}/params");
        let mut q = QueryBuf::new();
        q.push_opt_num("limit", limit);
        q.push_opt_num("offset", offset);
        self.signed_get(&path, &q.as_pairs()).await
    }

    pub async fn tag_summary(&self, id: &str) -> Result<Value, TailFinError> {
        let path = format!("/tag/{id}/summary");
        self.signed_get(&path, &[]).await
    }

    pub async fn balances_solana_subaccounts_address(
        &self,
        addresses: &str,
        pricing_id: &str,
        limit: Option<u32>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/balances/solana/subaccounts/address/{addresses}");
        let mut q = QueryBuf::new();
        q.push("pricingID", pricing_id);
        q.push_opt_num("limit", limit);
        self.signed_get(&path, &q.as_pairs()).await
    }

    pub async fn balances_solana_subaccounts_entity(
        &self,
        entities: &str,
        pricing_id: &str,
        limit: Option<u32>,
    ) -> Result<Value, TailFinError> {
        let path = format!("/balances/solana/subaccounts/entity/{entities}");
        let mut q = QueryBuf::new();
        q.push("pricingID", pricing_id);
        q.push_opt_num("limit", limit);
        self.signed_get(&path, &q.as_pairs()).await
    }

    // ─── metadata / misc ─────────────────────────────────────────────────

    pub async fn chains(&self) -> Result<Value, TailFinError> {
        self.signed_get("/chains", &[]).await
    }

    pub async fn networks_status(&self) -> Result<Value, TailFinError> {
        self.signed_get("/networks/status", &[]).await
    }

    pub async fn networks_history(&self, chain: &str) -> Result<Value, TailFinError> {
        let path = format!("/networks/history/{chain}");
        self.signed_get(&path, &[]).await
    }

    pub async fn altcoin_index(&self) -> Result<Value, TailFinError> {
        self.signed_get("/marketdata/altcoin_index", &[]).await
    }

    pub async fn arkm_circulating(&self) -> Result<Value, TailFinError> {
        self.signed_get("/arkm/circulating", &[]).await
    }
}

// ─── helpers ─────────────────────────────────────────────────────────────

fn current_unix_seconds() -> Result<String, TailFinError> {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs().to_string())
        .map_err(|e| TailFinError::Api(format!("system clock before epoch: {e}")))
}

fn build_signed_headers(ts: &str, payload: &str) -> Result<HeaderMap, TailFinError> {
    let mut h = HeaderMap::new();
    let to_hv = |s: &str, name: &'static str| {
        HeaderValue::from_str(s)
            .map_err(|e| TailFinError::Api(format!("invalid {name} header value: {e}")))
    };
    h.insert(
        ACCEPT,
        HeaderValue::from_static("application/json, text/plain, */*"),
    );
    h.insert(ORIGIN, HeaderValue::from_static(ORIGIN_HEADER));
    h.insert(REFERER, HeaderValue::from_static(REFERER_HEADER));
    h.insert("X-Timestamp", to_hv(ts, "X-Timestamp")?);
    h.insert("X-Payload", to_hv(payload, "X-Payload")?);
    Ok(h)
}

fn chains_pairs(chains: Option<&str>) -> Vec<(&str, &str)> {
    chains.map(|c| vec![("chains", c)]).unwrap_or_default()
}

/// Owned key/value pairs for query strings — used when values are computed
/// (e.g. `to_string()`'d numbers). Caller borrows back via `as_pairs()`.
struct QueryBuf {
    pairs: Vec<(&'static str, String)>,
}

impl QueryBuf {
    fn new() -> Self {
        Self { pairs: Vec::new() }
    }
    fn push(&mut self, k: &'static str, v: &str) {
        self.pairs.push((k, v.to_string()));
    }
    fn push_opt(&mut self, k: &'static str, v: Option<&str>) {
        if let Some(s) = v {
            self.pairs.push((k, s.to_string()));
        }
    }
    fn push_opt_bool(&mut self, k: &'static str, v: Option<bool>) {
        if let Some(b) = v {
            self.pairs
                .push((k, if b { "true".into() } else { "false".into() }));
        }
    }
    fn push_opt_num<N: std::fmt::Display>(&mut self, k: &'static str, v: Option<N>) {
        if let Some(n) = v {
            self.pairs.push((k, n.to_string()));
        }
    }
    fn as_pairs(&self) -> Vec<(&'static str, &str)> {
        self.pairs.iter().map(|(k, v)| (*k, v.as_str())).collect()
    }
}

/// Build the query-pairs for a `/transfers`-style request. Values are owned
/// because `base[]` is a Vec and counts like `limit` must be stringified.
fn transfers_query_pairs(q: &TransfersQuery<'_>) -> Vec<(&'static str, String)> {
    let mut out: Vec<(&'static str, String)> = Vec::new();
    if let Some(bases) = q.base {
        for b in bases {
            out.push(("base", (*b).to_string()));
        }
    }
    if let Some(f) = q.flow {
        out.push(("flow", f.to_string()));
    }
    if let Some(v) = q.usd_gte {
        out.push(("usdGte", v.to_string()));
    }
    if let Some(k) = q.sort_key {
        out.push(("sortKey", k.to_string()));
    }
    if let Some(d) = q.sort_dir {
        out.push(("sortDir", d.to_string()));
    }
    if let Some(l) = q.limit {
        out.push(("limit", l.to_string()));
    }
    if let Some(o) = q.offset {
        out.push(("offset", o.to_string()));
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn transfers_query_pairs_empty_when_default() {
        assert!(transfers_query_pairs(&TransfersQuery::default()).is_empty());
    }

    #[test]
    fn transfers_query_pairs_repeats_base() {
        let bases = ["0xaaa", "0xbbb"];
        let q = TransfersQuery {
            base: Some(&bases),
            flow: Some("all"),
            usd_gte: Some("1"),
            sort_key: Some("time"),
            sort_dir: Some("desc"),
            limit: Some(16),
            offset: Some(0),
        };
        let owned = transfers_query_pairs(&q);
        let pairs: Vec<(&str, &str)> = owned.iter().map(|(k, v)| (*k, v.as_str())).collect();
        assert_eq!(
            pairs,
            vec![
                ("base", "0xaaa"),
                ("base", "0xbbb"),
                ("flow", "all"),
                ("usdGte", "1"),
                ("sortKey", "time"),
                ("sortDir", "desc"),
                ("limit", "16"),
                ("offset", "0"),
            ]
        );
    }

    #[test]
    fn querybuf_skips_none() {
        let mut q = QueryBuf::new();
        q.push_opt("a", None);
        q.push_opt("b", Some("yes"));
        q.push_opt_num::<u32>("c", None);
        q.push_opt_num("d", Some(42_u32));
        q.push_opt_bool("e", None);
        q.push_opt_bool("f", Some(true));
        let v = q.as_pairs();
        assert_eq!(v, vec![("b", "yes"), ("d", "42"), ("f", "true")]);
    }
}