Skip to main content

cabalspy/
client.rs

1//! The HTTP client and its resource groups.
2
3use std::collections::HashMap;
4use std::time::{Duration, SystemTime, UNIX_EPOCH};
5
6use serde::de::DeserializeOwned;
7use serde_json::json;
8
9use crate::error::{error_from_body, error_from_status, ApiErrorBody, Error, RateLimit, Result};
10use crate::models::*;
11
12pub const DEFAULT_BASE_URL: &str = "https://api.cabalspy.xyz/v1";
13pub const DEFAULT_WS_URL: &str = "wss://stream.cabalspy.xyz";
14pub const BATCH_MAX_MINTS: usize = 100;
15/// The public demo key. Works as a normal key on REST and the websocket gateway,
16/// limited to 20 requests per IP per UTC day with 15 minute delayed data and at
17/// most 5 rows per list. See [`CabalSpy::demo`].
18pub const DEMO_API_KEY: &str = "demo";
19pub const BATCH_MAX_ADDRESSES: usize = 100;
20
21const SDK_USER_AGENT: &str = concat!("cabalspy-rust/", env!("CARGO_PKG_VERSION"));
22
23/// A list of query parameters, built as owned strings.
24type Query = Vec<(String, String)>;
25
26/// Adds a parameter when the value is present.
27fn push_opt<T: ToString>(query: &mut Query, key: &str, value: Option<T>) {
28    if let Some(value) = value {
29        query.push((key.to_string(), value.to_string()));
30    }
31}
32
33fn push<T: ToString>(query: &mut Query, key: &str, value: T) {
34    query.push((key.to_string(), value.to_string()));
35}
36
37fn header_u64(headers: &reqwest::header::HeaderMap, name: &str) -> Option<u64> {
38    headers
39        .get(name)
40        .and_then(|value| value.to_str().ok())
41        .and_then(|text| text.parse::<u64>().ok())
42}
43
44/// Cheap jitter without pulling in a random number generator.
45fn jitter_ms() -> u64 {
46    SystemTime::now()
47        .duration_since(UNIX_EPOCH)
48        .map(|d| (d.subsec_nanos() / 1_000_000) as u64 % 250)
49        .unwrap_or(0)
50}
51
52fn backoff(attempt: u32, last: Option<&Error>) -> Duration {
53    if let Some(Error::RateLimited {
54        retry_after: Some(seconds),
55        ..
56    }) = last
57    {
58        return Duration::from_secs((*seconds).min(60));
59    }
60    let base = 500u64.saturating_mul(1u64 << attempt.saturating_sub(1).min(4));
61    Duration::from_millis(base.min(8_000) + jitter_ms())
62}
63
64/// Reads the top-level `demo` object, falling back to the `X-Demo-Remaining`
65/// header for the remaining budget.
66fn demo_info(raw: Option<serde_json::Value>, remaining: Option<u64>) -> Option<DemoInfo> {
67    let parsed = raw.and_then(|value| serde_json::from_value::<DemoInfo>(value).ok());
68    match (parsed, remaining) {
69        (Some(mut info), remaining) => {
70            info.remaining_today = info.remaining_today.or(remaining);
71            Some(info)
72        }
73        (None, Some(remaining)) => Some(DemoInfo {
74            remaining_today: Some(remaining),
75            ..Default::default()
76        }),
77        (None, None) => None,
78    }
79}
80
81/// Rejects a chain and wallet type combination the API does not have.
82fn check_type(chain: Chain, wallet_type: WalletType) -> Result<()> {
83    if chain.supports(wallet_type) {
84        return Ok(());
85    }
86    let allowed: Vec<&str> = chain.wallet_types().iter().map(|t| t.as_str()).collect();
87    Err(Error::InvalidRequest {
88        message: format!(
89            "{chain} has no {wallet_type} wallets; it supports: {}",
90            allowed.join(", ")
91        ),
92    })
93}
94
95// ═══════════════════════════════════════════════════════════════════════════
96//  CLIENT
97// ═══════════════════════════════════════════════════════════════════════════
98
99/// Builder for [`CabalSpy`].
100#[derive(Debug, Clone, Default)]
101pub struct CabalSpyBuilder {
102    api_key: Option<String>,
103    base_url: Option<String>,
104    ws_url: Option<String>,
105    timeout: Option<Duration>,
106    max_retries: Option<u32>,
107}
108
109impl CabalSpyBuilder {
110    /// The API key. Falls back to the `CABALSPY_API_KEY` environment variable.
111    pub fn api_key(mut self, key: impl Into<String>) -> Self {
112        self.api_key = Some(key.into());
113        self
114    }
115
116    /// Uses the public demo key, [`DEMO_API_KEY`], instead of your own.
117    ///
118    /// Meant for trying the API without signing up: 20 requests per IP per UTC
119    /// day shared between REST and websocket, data delayed by 15 minutes, at most
120    /// 5 rows per list. When the budget is spent requests fail with
121    /// [`Error::DemoLimit`].
122    pub fn demo(self) -> Self {
123        self.api_key(DEMO_API_KEY)
124    }
125
126    /// REST base URL including `/v1`.
127    pub fn base_url(mut self, url: impl Into<String>) -> Self {
128        self.base_url = Some(url.into());
129        self
130    }
131
132    /// Websocket gateway URL.
133    pub fn ws_url(mut self, url: impl Into<String>) -> Self {
134        self.ws_url = Some(url.into());
135        self
136    }
137
138    /// Per-request timeout. Default 30 seconds.
139    pub fn timeout(mut self, timeout: Duration) -> Self {
140        self.timeout = Some(timeout);
141        self
142    }
143
144    /// Retries on 429, 5xx and network errors. Default 2.
145    pub fn max_retries(mut self, retries: u32) -> Self {
146        self.max_retries = Some(retries);
147        self
148    }
149
150    pub fn build(self) -> Result<CabalSpy> {
151        let api_key = self
152            .api_key
153            .or_else(|| std::env::var("CABALSPY_API_KEY").ok())
154            .ok_or(Error::MissingApiKey)?;
155
156        let timeout = self.timeout.unwrap_or(Duration::from_secs(30));
157        let http = reqwest::Client::builder().timeout(timeout).build()?;
158
159        Ok(CabalSpy {
160            http,
161            api_key,
162            base_url: self
163                .base_url
164                .or_else(|| std::env::var("CABALSPY_BASE_URL").ok())
165                .unwrap_or_else(|| DEFAULT_BASE_URL.to_string())
166                .trim_end_matches('/')
167                .to_string(),
168            ws_url: self
169                .ws_url
170                .or_else(|| std::env::var("CABALSPY_WS_URL").ok())
171                .unwrap_or_else(|| DEFAULT_WS_URL.to_string())
172                .trim_end_matches('/')
173                .to_string(),
174            max_retries: self.max_retries.unwrap_or(2),
175        })
176    }
177}
178
179/// Asynchronous client for the CabalSpy API.
180///
181/// ```no_run
182/// # async fn run() -> Result<(), cabalspy::Error> {
183/// use cabalspy::{CabalSpy, Chain, Period, WalletType};
184///
185/// let client = CabalSpy::from_env()?;
186/// let wallet = client.wallets().lookup("As7HjL7...").await?;
187/// println!("{:?}", wallet.data);
188/// # Ok(()) }
189/// ```
190#[derive(Debug, Clone)]
191pub struct CabalSpy {
192    http: reqwest::Client,
193    api_key: String,
194    base_url: String,
195    ws_url: String,
196    max_retries: u32,
197}
198
199impl CabalSpy {
200    pub fn builder() -> CabalSpyBuilder {
201        CabalSpyBuilder::default()
202    }
203
204    /// Builds a client with an explicit API key and all other defaults.
205    pub fn new(api_key: impl Into<String>) -> Result<Self> {
206        CabalSpyBuilder::default().api_key(api_key).build()
207    }
208
209    /// Builds a client on the public demo key. No signup needed.
210    ///
211    /// ```no_run
212    /// # async fn run() -> Result<(), cabalspy::Error> {
213    /// use cabalspy::{CabalSpy, Chain, WalletType};
214    ///
215    /// let client = CabalSpy::demo()?;
216    /// let kols = client.wallets().list(Chain::Solana, WalletType::Kol, None, None).await?;
217    /// println!("{:?}", kols.demo.and_then(|d| d.remaining_today));
218    /// # Ok(()) }
219    /// ```
220    ///
221    /// Limits: 20 requests per IP per UTC day, data delayed by 15 minutes, at
222    /// most 5 rows per list. For realtime data get a free test key at
223    /// <https://apidashboard.cabalspy.xyz/>, or pay per call with x402.
224    pub fn demo() -> Result<Self> {
225        CabalSpyBuilder::default().demo().build()
226    }
227
228    /// True when the client is using the public demo key.
229    pub fn is_demo(&self) -> bool {
230        self.api_key == DEMO_API_KEY
231    }
232
233    /// Builds a client, reading the key from `CABALSPY_API_KEY`.
234    pub fn from_env() -> Result<Self> {
235        CabalSpyBuilder::default().build()
236    }
237
238    pub fn base_url(&self) -> &str {
239        &self.base_url
240    }
241
242    pub fn ws_url(&self) -> &str {
243        &self.ws_url
244    }
245
246    /// The gateway URL including the auth query parameter.
247    pub fn websocket_url(&self) -> String {
248        format!("{}/?apiKey={}", self.ws_url, self.api_key)
249    }
250
251    // ── resources ────────────────────────────────────────────────────────
252
253    pub fn system(&self) -> System<'_> {
254        System { client: self }
255    }
256    pub fn wallets(&self) -> Wallets<'_> {
257        Wallets { client: self }
258    }
259    pub fn tokens(&self) -> Tokens<'_> {
260        Tokens { client: self }
261    }
262    pub fn transactions(&self) -> Transactions<'_> {
263        Transactions { client: self }
264    }
265    pub fn signals(&self) -> Signals<'_> {
266        Signals { client: self }
267    }
268    pub fn analytics(&self) -> Analytics<'_> {
269        Analytics { client: self }
270    }
271    pub fn calls(&self) -> Calls<'_> {
272        Calls { client: self }
273    }
274    pub fn bundle(&self) -> Bundle<'_> {
275        Bundle { client: self }
276    }
277
278    // ── plumbing ─────────────────────────────────────────────────────────
279
280    /// Any GET, deserialized into `T`. Use this for endpoints not yet wrapped.
281    pub async fn get<T: DeserializeOwned>(&self, path: &str, query: Query) -> Result<Envelope<T>> {
282        self.send(reqwest::Method::GET, path, query, None).await
283    }
284
285    /// Any POST, deserialized into `T`.
286    pub async fn post<T: DeserializeOwned>(
287        &self,
288        path: &str,
289        body: serde_json::Value,
290    ) -> Result<Envelope<T>> {
291        self.send(reqwest::Method::POST, path, Vec::new(), Some(body))
292            .await
293    }
294
295    async fn send<T: DeserializeOwned>(
296        &self,
297        method: reqwest::Method,
298        path: &str,
299        query: Query,
300        body: Option<serde_json::Value>,
301    ) -> Result<Envelope<T>> {
302        let url = format!("{}{}", self.base_url, path);
303        let mut last: Option<Error> = None;
304
305        for attempt in 0..=self.max_retries {
306            if attempt > 0 {
307                tokio::time::sleep(backoff(attempt, last.as_ref())).await;
308            }
309
310            let mut request = self
311                .http
312                .request(method.clone(), &url)
313                .bearer_auth(&self.api_key)
314                .header(reqwest::header::USER_AGENT, SDK_USER_AGENT)
315                .header(reqwest::header::ACCEPT, "application/json")
316                .query(&query);
317            if let Some(ref payload) = body {
318                request = request.json(payload);
319            }
320
321            let response = match request.send().await {
322                Ok(response) => response,
323                Err(err) => {
324                    let error = Error::Transport(err);
325                    if error.is_retryable() && attempt < self.max_retries {
326                        last = Some(error);
327                        continue;
328                    }
329                    return Err(error);
330                }
331            };
332
333            let status = response.status().as_u16();
334            let rate_limit = RateLimit {
335                limit: header_u64(response.headers(), "x-ratelimit-limit"),
336                remaining: header_u64(response.headers(), "x-ratelimit-remaining"),
337                reset: header_u64(response.headers(), "x-ratelimit-reset"),
338            };
339            let retry_after = header_u64(response.headers(), "retry-after");
340
341            let demo_remaining = header_u64(response.headers(), "x-demo-remaining");
342            let text = response.text().await.unwrap_or_default();
343
344            if status >= 400 {
345                let error = error_from_body(
346                    status,
347                    &text,
348                    format!("HTTP {status} on {method} {path}"),
349                    rate_limit,
350                    retry_after,
351                );
352                if error.is_retryable() && attempt < self.max_retries {
353                    last = Some(error);
354                    continue;
355                }
356                return Err(error);
357            }
358
359            let raw: RawEnvelope<T> = serde_json::from_str(&text).map_err(|err| {
360                Error::Decode(format!("{method} {path}: {err}"))
361            })?;
362
363            return Ok(Envelope {
364                data: raw.data,
365                pagination: raw.pagination,
366                meta: raw.meta,
367                rate_limit,
368                status,
369                demo: demo_info(raw.demo, demo_remaining),
370            });
371        }
372
373        Err(last.unwrap_or(Error::Decode(format!("request failed: {method} {path}"))))
374    }
375
376    /// For `/health` and `/meta`, which answer without the success/data envelope.
377    async fn get_plain<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
378        let url = format!("{}{}", self.base_url, path);
379        let response = self
380            .http
381            .get(&url)
382            .header(reqwest::header::USER_AGENT, SDK_USER_AGENT)
383            .send()
384            .await?;
385        let status = response.status().as_u16();
386        let text = response.text().await.unwrap_or_default();
387        if status >= 400 {
388            return Err(error_from_status(
389                status,
390                ApiErrorBody {
391                    code: format!("http_{status}"),
392                    message: format!("HTTP {status} on GET {path}"),
393                    ..Default::default()
394                },
395                RateLimit::default(),
396                None,
397            ));
398        }
399        serde_json::from_str(&text).map_err(|err| Error::Decode(format!("GET {path}: {err}")))
400    }
401}
402
403// ═══════════════════════════════════════════════════════════════════════════
404//  OPTIONAL PARAMETERS
405// ═══════════════════════════════════════════════════════════════════════════
406
407/// Optional parameters for [`Wallets::leaderboard`].
408#[derive(Debug, Clone, Default)]
409pub struct LeaderboardOpts {
410    /// Defaults to `kol` server side.
411    pub wallet_type: Option<WalletType>,
412    /// Defaults to `1d` server side.
413    pub period: Option<Period>,
414    /// Omitting this returns every entry.
415    pub limit: Option<u32>,
416    pub cursor: Option<String>,
417}
418
419/// Optional parameters for the feed endpoints.
420///
421/// `seconds`, `minutes` and `hours` are alternatives; the server clamps anything
422/// beyond 60 minutes for `timerange` and 24 hours for `count` and `volume`, and
423/// reports the clamp in `warnings`.
424#[derive(Debug, Clone, Default)]
425pub struct FeedOpts {
426    pub seconds: Option<u64>,
427    pub minutes: Option<u64>,
428    pub hours: Option<u64>,
429    pub limit: Option<u32>,
430    /// Restrict to one token.
431    pub mint: Option<String>,
432}
433
434/// Optional parameters for [`Signals::list`].
435///
436/// Setting any of the gated filters switches the server into gated mode, which
437/// applies an AND gate across wallet types.
438#[derive(Debug, Clone, Default)]
439pub struct SignalOpts {
440    pub limit: Option<u32>,
441    /// Minimum number of buying wallets for a cluster. Server default 3.
442    pub min_wallets: Option<u32>,
443    /// Minimum buy value in the chain's native currency.
444    pub min_value: Option<f64>,
445    /// Observation window in hours. Server default 1.
446    pub hours: Option<u32>,
447    /// Entry thresholds for kol as CSV, for example `"3,5,10"`.
448    pub kol: Option<String>,
449    pub smart: Option<String>,
450    pub kol_min_buy: Option<f64>,
451    pub kol_max_buy: Option<f64>,
452    /// Exit thresholds as remaining holders, CSV in descending order.
453    pub kol_exit: Option<String>,
454    pub smart_min_buy: Option<f64>,
455    pub smart_max_buy: Option<f64>,
456    pub smart_exit: Option<String>,
457    /// Comma separated wallet addresses.
458    pub include_wallets: Option<String>,
459    pub exclude_wallets: Option<String>,
460    /// Between 0 and 100.
461    pub min_win_rate: Option<f64>,
462    /// Token age in hours.
463    pub min_token_age: Option<f64>,
464    pub max_token_age: Option<f64>,
465}
466
467impl SignalOpts {
468    fn apply(self, query: &mut Query) {
469        push_opt(query, "limit", self.limit);
470        push_opt(query, "min_wallets", self.min_wallets);
471        push_opt(query, "min_value", self.min_value);
472        push_opt(query, "hours", self.hours);
473        push_opt(query, "kol", self.kol);
474        push_opt(query, "smart", self.smart);
475        push_opt(query, "kol_min_buy", self.kol_min_buy);
476        push_opt(query, "kol_max_buy", self.kol_max_buy);
477        push_opt(query, "kol_exit", self.kol_exit);
478        push_opt(query, "smart_min_buy", self.smart_min_buy);
479        push_opt(query, "smart_max_buy", self.smart_max_buy);
480        push_opt(query, "smart_exit", self.smart_exit);
481        push_opt(query, "include_wallets", self.include_wallets);
482        push_opt(query, "exclude_wallets", self.exclude_wallets);
483        push_opt(query, "min_win_rate", self.min_win_rate);
484        push_opt(query, "min_token_age", self.min_token_age);
485        push_opt(query, "max_token_age", self.max_token_age);
486    }
487}
488
489/// Optional parameters for [`Tokens::transactions_with`] and [`Tokens::holders_with`].
490#[derive(Debug, Clone, Default)]
491pub struct TokenOpts {
492    /// Restrict to one wallet type. `None` merges every type of the chain.
493    pub wallet_type: Option<WalletType>,
494    pub limit: Option<u32>,
495    /// `pagination.next_cursor` of the previous page, sent with the same limit.
496    pub cursor: Option<String>,
497    /// Transactions only: trades at or after this time (Unix seconds, Unix
498    /// milliseconds or ISO 8601 in UTC). Usually the `created_at` of the newest
499    /// trade you already have. A poll that finds nothing new costs 0 credits.
500    /// The bound is inclusive, so deduplicate by `tx_signature`. Ignored by
501    /// `holders_with`.
502    pub since: Option<String>,
503}
504
505/// Optional parameters for [`Calls::list`].
506#[derive(Debug, Clone, Default)]
507pub struct CallsOpts {
508    /// Empty for every chain. Base has no calls.
509    pub chains: Vec<Chain>,
510    /// Empty for every tier.
511    pub tiers: Vec<CallTier>,
512    /// ISO 8601 or Unix seconds.
513    pub since: Option<String>,
514    pub until: Option<String>,
515    /// 1 to 200. Server default 50.
516    pub limit: Option<u32>,
517    pub cursor: Option<String>,
518}
519
520fn check_call_chains(chains: &[Chain]) -> Result<()> {
521    if chains.contains(&Chain::Base) {
522        return Err(Error::InvalidRequest {
523            message: "base has no calls; calls cover solana, bnb, eth and rh".to_string(),
524        });
525    }
526    Ok(())
527}
528
529fn push_list<T: ToString>(query: &mut Query, key: &str, values: &[T]) {
530    if !values.is_empty() {
531        let joined: Vec<String> = values.iter().map(|v| v.to_string()).collect();
532        push(query, key, joined.join(","));
533    }
534}
535
536impl FeedOpts {
537    fn apply(self, query: &mut Query) {
538        push_opt(query, "seconds", self.seconds);
539        push_opt(query, "minutes", self.minutes);
540        push_opt(query, "hours", self.hours);
541        push_opt(query, "limit", self.limit);
542        push_opt(query, "mint", self.mint);
543    }
544}
545
546// ═══════════════════════════════════════════════════════════════════════════
547//  RESOURCES
548// ═══════════════════════════════════════════════════════════════════════════
549
550/// `/v1/health` and `/v1/meta`.
551#[derive(Debug)]
552pub struct System<'a> {
553    client: &'a CabalSpy,
554}
555
556impl System<'_> {
557    /// Redis, MySQL and websocket status per chain and wallet type.
558    pub async fn health(&self) -> Result<HealthResponse> {
559        self.client.get_plain("/health").await
560    }
561
562    /// Available chains, wallet types, periods, limits and wallet counts.
563    pub async fn meta(&self) -> Result<MetaResponse> {
564        self.client.get_plain("/meta").await
565    }
566}
567
568/// Wallet endpoints.
569#[derive(Debug)]
570pub struct Wallets<'a> {
571    client: &'a CabalSpy,
572}
573
574impl Wallets<'_> {
575    /// `GET /v1/wallets` — every tracked wallet for one chain and wallet type.
576    ///
577    /// Omitting `limit` returns every wallet.
578    pub async fn list(
579        &self,
580        chain: Chain,
581        wallet_type: WalletType,
582        limit: Option<u32>,
583        cursor: Option<String>,
584    ) -> Result<Envelope<serde_json::Value>> {
585        check_type(chain, wallet_type)?;
586        let mut query = Query::new();
587        push(&mut query, "blockchain", chain);
588        push(&mut query, "type", wallet_type);
589        push_opt(&mut query, "limit", limit);
590        push_opt(&mut query, "cursor", cursor);
591        self.client.get("/wallets", query).await
592    }
593
594    /// `GET /v1/wallets/history` — trade history. Server default 500, maximum 1000.
595    ///
596    /// This endpoint nests its pagination inside `data` rather than putting it on
597    /// the envelope, so `Envelope::pagination` is `None` here. Read
598    /// `data["pagination"]["next_cursor"]` instead.
599    pub async fn history(
600        &self,
601        chain: Chain,
602        address: &str,
603        limit: Option<u32>,
604        cursor: Option<String>,
605    ) -> Result<Envelope<serde_json::Value>> {
606        let mut query = Query::new();
607        push(&mut query, "blockchain", chain);
608        push(&mut query, "address", address);
609        push_opt(&mut query, "limit", limit);
610        push_opt(&mut query, "cursor", cursor);
611        self.client.get("/wallets/history", query).await
612    }
613
614    /// `GET /v1/wallets/lookup` — searches an address across all chains and types.
615    ///
616    /// Takes no chain argument by design. For EVM chains the same address can be
617    /// tracked on several of them, and the endpoint returns the first match in the
618    /// server's registry order, which may not be the chain you meant.
619    pub async fn lookup(&self, address: &str) -> Result<Envelope<serde_json::Value>> {
620        let mut query = Query::new();
621        push(&mut query, "address", address);
622        self.client.get("/wallets/lookup", query).await
623    }
624
625    /// `GET /v1/wallets/leaderboard` — ranking for the given period.
626    pub async fn leaderboard(
627        &self,
628        chain: Chain,
629        opts: LeaderboardOpts,
630    ) -> Result<Envelope<serde_json::Value>> {
631        if let Some(wallet_type) = opts.wallet_type {
632            check_type(chain, wallet_type)?;
633        }
634        let mut query = Query::new();
635        push(&mut query, "blockchain", chain);
636        push_opt(&mut query, "type", opts.wallet_type);
637        push_opt(&mut query, "period", opts.period);
638        push_opt(&mut query, "limit", opts.limit);
639        push_opt(&mut query, "cursor", opts.cursor);
640        self.client.get("/wallets/leaderboard", query).await
641    }
642
643    /// `GET /v1/wallets/tracker` — period stats and open positions for one wallet.
644    pub async fn tracker(
645        &self,
646        chain: Chain,
647        address: &str,
648        period: Option<Period>,
649    ) -> Result<Envelope<WalletTracker>> {
650        let mut query = Query::new();
651        push(&mut query, "blockchain", chain);
652        push(&mut query, "address", address);
653        push_opt(&mut query, "period", period);
654        self.client.get("/wallets/tracker", query).await
655    }
656
657    /// `GET /v1/wallets/holdings` — current onchain holdings, period independent.
658    pub async fn holdings(
659        &self,
660        chain: Chain,
661        address: &str,
662    ) -> Result<Envelope<serde_json::Value>> {
663        let mut query = Query::new();
664        push(&mut query, "blockchain", chain);
665        push(&mut query, "address", address);
666        self.client.get("/wallets/holdings", query).await
667    }
668
669    /// `GET /v1/wallet/pnl_calendar` — daily PNL calendar.
670    ///
671    /// This endpoint only exists under `/wallet/`, singular.
672    pub async fn pnl_calendar(
673        &self,
674        chain: Chain,
675        address: &str,
676    ) -> Result<Envelope<serde_json::Value>> {
677        let mut query = Query::new();
678        push(&mut query, "blockchain", chain);
679        push(&mut query, "address", address);
680        self.client.get("/wallet/pnl_calendar", query).await
681    }
682
683    /// `GET /v1/wallets/connections` — wallets whose traded tokens overlap, 30 days.
684    pub async fn connections(
685        &self,
686        chain: Chain,
687        address: &str,
688        limit: Option<u32>,
689    ) -> Result<Envelope<serde_json::Value>> {
690        let mut query = Query::new();
691        push(&mut query, "blockchain", chain);
692        push(&mut query, "address", address);
693        push_opt(&mut query, "limit", limit);
694        self.client.get("/wallets/connections", query).await
695    }
696
697    /// `POST /v1/wallets/batch` — up to 100 addresses in one request.
698    pub async fn batch(
699        &self,
700        chain: Chain,
701        wallet_type: WalletType,
702        addresses: &[String],
703        fields: Option<&[String]>,
704        period: Option<Period>,
705    ) -> Result<Envelope<serde_json::Value>> {
706        check_type(chain, wallet_type)?;
707        if addresses.is_empty() {
708            return Err(Error::InvalidRequest {
709                message: "addresses must not be empty".to_string(),
710            });
711        }
712        if addresses.len() > BATCH_MAX_ADDRESSES {
713            return Err(Error::InvalidRequest {
714                message: format!(
715                    "at most {BATCH_MAX_ADDRESSES} addresses per request, received {}",
716                    addresses.len()
717                ),
718            });
719        }
720        let mut body = json!({
721            "blockchain": chain.as_str(),
722            "type": wallet_type.as_str(),
723            "addresses": addresses,
724        });
725        if let Some(period) = period {
726            body["period"] = json!(period.as_str());
727        }
728        if let Some(fields) = fields {
729            body["fields"] = json!(fields);
730        }
731        self.client.post("/wallets/batch", body).await
732    }
733}
734
735fn token_query(chain: Chain, mint: &str, opts: &TokenOpts) -> Result<Query> {
736    if let Some(wallet_type) = opts.wallet_type {
737        check_type(chain, wallet_type)?;
738    }
739    let mut query = Query::new();
740    push(&mut query, "blockchain", chain);
741    push(&mut query, "mint", mint);
742    push_opt(&mut query, "type", opts.wallet_type);
743    push_opt(&mut query, "limit", opts.limit);
744    push_opt(&mut query, "cursor", opts.cursor.clone());
745    Ok(query)
746}
747
748/// Token endpoints.
749#[derive(Debug)]
750pub struct Tokens<'a> {
751    client: &'a CabalSpy,
752}
753
754impl Tokens<'_> {
755    /// `GET /v1/tokens/transactions` — trades by tracked wallets in this token.
756    pub async fn transactions(
757        &self,
758        chain: Chain,
759        mint: &str,
760        wallet_type: Option<WalletType>,
761        limit: Option<u32>,
762    ) -> Result<Envelope<serde_json::Value>> {
763        if let Some(wallet_type) = wallet_type {
764            check_type(chain, wallet_type)?;
765        }
766        let mut query = Query::new();
767        push(&mut query, "blockchain", chain);
768        push(&mut query, "mint", mint);
769        push_opt(&mut query, "type", wallet_type);
770        push_opt(&mut query, "limit", limit);
771        self.client.get("/tokens/transactions", query).await
772    }
773
774    /// `GET /v1/tokens/transactions` with paging and polling: see [`TokenOpts`].
775    ///
776    /// Poll with `since` to get only new trades, then follow
777    /// `pagination.next_cursor` with `cursor`.
778    pub async fn transactions_with(
779        &self,
780        chain: Chain,
781        mint: &str,
782        opts: TokenOpts,
783    ) -> Result<Envelope<serde_json::Value>> {
784        let mut query = token_query(chain, mint, &opts)?;
785        push_opt(&mut query, "since", opts.since);
786        self.client.get("/tokens/transactions", query).await
787    }
788
789    /// `GET /v1/tokens/holders` with paging: see [`TokenOpts`] (`since` is ignored).
790    pub async fn holders_with(
791        &self,
792        chain: Chain,
793        mint: &str,
794        opts: TokenOpts,
795    ) -> Result<Envelope<serde_json::Value>> {
796        let query = token_query(chain, mint, &opts)?;
797        self.client.get("/tokens/holders", query).await
798    }
799
800    /// `GET /v1/tokens/stats` — aggregated token statistics.
801    ///
802    /// Passing `None` for the wallet type merges every type of that chain.
803    /// Market cap and price are filled on every chain; `market_cap_source` says
804    /// whether the value is live or taken from the last tracked trade.
805    pub async fn stats(
806        &self,
807        chain: Chain,
808        mint: &str,
809        wallet_type: Option<WalletType>,
810    ) -> Result<Envelope<TokenStats>> {
811        if let Some(wallet_type) = wallet_type {
812            check_type(chain, wallet_type)?;
813        }
814        let mut query = Query::new();
815        push(&mut query, "blockchain", chain);
816        push(&mut query, "mint", mint);
817        push_opt(&mut query, "type", wallet_type);
818        self.client.get("/tokens/stats", query).await
819    }
820
821    /// `GET /v1/tokens/holders` — tracked holders, sorted by balance.
822    pub async fn holders(
823        &self,
824        chain: Chain,
825        mint: &str,
826        wallet_type: Option<WalletType>,
827        limit: Option<u32>,
828    ) -> Result<Envelope<serde_json::Value>> {
829        if let Some(wallet_type) = wallet_type {
830            check_type(chain, wallet_type)?;
831        }
832        let mut query = Query::new();
833        push(&mut query, "blockchain", chain);
834        push(&mut query, "mint", mint);
835        push_opt(&mut query, "type", wallet_type);
836        push_opt(&mut query, "limit", limit);
837        self.client.get("/tokens/holders", query).await
838    }
839
840    /// `POST /v1/tokens/batch` — up to 100 mints in one request.
841    pub async fn batch(
842        &self,
843        chain: Chain,
844        wallet_type: WalletType,
845        mints: &[String],
846        fields: Option<&[String]>,
847    ) -> Result<Envelope<serde_json::Value>> {
848        check_type(chain, wallet_type)?;
849        if mints.is_empty() {
850            return Err(Error::InvalidRequest {
851                message: "mints must not be empty".to_string(),
852            });
853        }
854        if mints.len() > BATCH_MAX_MINTS {
855            return Err(Error::InvalidRequest {
856                message: format!(
857                    "at most {BATCH_MAX_MINTS} mints per request, received {}",
858                    mints.len()
859                ),
860            });
861        }
862        let mut body = json!({
863            "blockchain": chain.as_str(),
864            "type": wallet_type.as_str(),
865            "mints": mints,
866        });
867        if let Some(fields) = fields {
868            body["fields"] = json!(fields);
869        }
870        self.client.post("/tokens/batch", body).await
871    }
872}
873
874/// The transaction feed.
875#[derive(Debug)]
876pub struct Transactions<'a> {
877    client: &'a CabalSpy,
878}
879
880impl Transactions<'_> {
881    /// `GET /v1/transactions/latest` — most recent trades by tracked wallets.
882    pub async fn latest(
883        &self,
884        chain: Chain,
885        wallet_type: WalletType,
886        opts: FeedOpts,
887    ) -> Result<Envelope<TransactionsList>> {
888        check_type(chain, wallet_type)?;
889        let mut query = Query::new();
890        push(&mut query, "blockchain", chain);
891        push(&mut query, "type", wallet_type);
892        opts.apply(&mut query);
893        self.client.get("/transactions/latest", query).await
894    }
895
896    /// `GET /v1/transactions/timerange` — trades in the last N, capped at 60 minutes.
897    pub async fn timerange(
898        &self,
899        chain: Chain,
900        wallet_type: WalletType,
901        opts: FeedOpts,
902    ) -> Result<Envelope<TransactionsList>> {
903        check_type(chain, wallet_type)?;
904        let mut query = Query::new();
905        push(&mut query, "blockchain", chain);
906        push(&mut query, "type", wallet_type);
907        opts.apply(&mut query);
908        self.client.get("/transactions/timerange", query).await
909    }
910
911    /// `GET /v1/transactions/count` — trade count and unique wallets, up to 24 hours.
912    pub async fn count(
913        &self,
914        chain: Chain,
915        wallet_type: WalletType,
916        opts: FeedOpts,
917    ) -> Result<Envelope<CountResponse>> {
918        check_type(chain, wallet_type)?;
919        let mut query = Query::new();
920        push(&mut query, "blockchain", chain);
921        push(&mut query, "type", wallet_type);
922        opts.apply(&mut query);
923        self.client.get("/transactions/count", query).await
924    }
925
926    /// `GET /v1/transactions/volume` — volume in native currency and USD, up to 24 hours.
927    pub async fn volume(
928        &self,
929        chain: Chain,
930        wallet_type: WalletType,
931        opts: FeedOpts,
932    ) -> Result<Envelope<VolumeResponse>> {
933        check_type(chain, wallet_type)?;
934        let mut query = Query::new();
935        push(&mut query, "blockchain", chain);
936        push(&mut query, "type", wallet_type);
937        opts.apply(&mut query);
938        self.client.get("/transactions/volume", query).await
939    }
940}
941
942/// Cluster, entry and exit signals.
943#[derive(Debug)]
944pub struct Signals<'a> {
945    client: &'a CabalSpy,
946}
947
948impl Signals<'_> {
949    /// `GET /v1/signals` — live clusters, entries and exits.
950    ///
951    /// Smart money is unavailable on Ethereum.
952    pub async fn list(
953        &self,
954        chain: Chain,
955        wallet_type: WalletType,
956        mode: SignalMode,
957        opts: SignalOpts,
958    ) -> Result<Envelope<SignalsResponse>> {
959        check_type(chain, wallet_type)?;
960        let mut query = Query::new();
961        push(&mut query, "blockchain", chain);
962        push(&mut query, "type", wallet_type);
963        push(&mut query, "mode", mode.as_str());
964        opts.apply(&mut query);
965        self.client.get("/signals", query).await
966    }
967
968    /// `GET /v1/signals/history` — backtest over 7, 30 or 90 days, or `"all"`.
969    pub async fn history(
970        &self,
971        chain: Chain,
972        wallet_type: WalletType,
973        days: Option<&str>,
974        limit: Option<u32>,
975        mode: Option<SignalMode>,
976    ) -> Result<Envelope<serde_json::Value>> {
977        check_type(chain, wallet_type)?;
978        let mut query = Query::new();
979        push(&mut query, "blockchain", chain);
980        push(&mut query, "type", wallet_type);
981        push_opt(&mut query, "days", days);
982        push_opt(&mut query, "limit", limit);
983        push_opt(&mut query, "mode", mode.map(|m| m.as_str()));
984        self.client.get("/signals/history", query).await
985    }
986}
987
988/// Aggregate analytics.
989#[derive(Debug)]
990pub struct Analytics<'a> {
991    client: &'a CabalSpy,
992}
993
994impl Analytics<'_> {
995    /// `GET /v1/analytics` — volume trend, most traded, win rate or top performers.
996    pub async fn get(
997        &self,
998        chain: Chain,
999        wallet_type: WalletType,
1000        mode: AnalyticsMode,
1001        period: Option<Period>,
1002        limit: Option<u32>,
1003    ) -> Result<Envelope<serde_json::Value>> {
1004        check_type(chain, wallet_type)?;
1005        let mut query = Query::new();
1006        push(&mut query, "blockchain", chain);
1007        push(&mut query, "type", wallet_type);
1008        push(&mut query, "mode", mode.as_str());
1009        push_opt(&mut query, "period", period);
1010        push_opt(&mut query, "limit", limit);
1011        self.client.get("/analytics", query).await
1012    }
1013}
1014
1015/// KOL bundle detection. Solana only.
1016#[derive(Debug)]
1017pub struct Bundle<'a> {
1018    client: &'a CabalSpy,
1019}
1020
1021impl Bundle<'_> {
1022    /// `GET /v1/bundle` — snapshot of the bundle stream.
1023    pub async fn get(&self, mint: &str) -> Result<Envelope<BundleResponse>> {
1024        let mut query = Query::new();
1025        push(&mut query, "blockchain", Chain::Solana);
1026        push(&mut query, "mint", mint);
1027        self.client.get("/bundle", query).await
1028    }
1029}
1030
1031/// The curated CabalSpy calls, the same ones posted in Discord.
1032#[derive(Debug)]
1033pub struct Calls<'a> {
1034    client: &'a CabalSpy,
1035}
1036
1037impl Calls<'_> {
1038    /// `GET /v1/calls` — newest first, each with its 24 h performance.
1039    ///
1040    /// `performance.status` is `pending` for about two days, until the call has
1041    /// been measured. Follow `pagination.next_cursor` for older calls.
1042    pub async fn list(&self, opts: CallsOpts) -> Result<Envelope<Vec<Call>>> {
1043        check_call_chains(&opts.chains)?;
1044        let mut query = Query::new();
1045        push_list(&mut query, "blockchain", &opts.chains);
1046        push_list(&mut query, "tier", &opts.tiers);
1047        push_opt(&mut query, "since", opts.since);
1048        push_opt(&mut query, "until", opts.until);
1049        push_opt(&mut query, "limit", opts.limit);
1050        push_opt(&mut query, "cursor", opts.cursor);
1051        self.client.get("/calls", query).await
1052    }
1053
1054    /// `GET /v1/calls/stats` — hit rates (2x, 5x, 10x within 24 h) per chain and tier.
1055    pub async fn stats(
1056        &self,
1057        period: Option<CallStatsPeriod>,
1058        chains: &[Chain],
1059        tiers: &[CallTier],
1060    ) -> Result<Envelope<CallStatsResponse>> {
1061        check_call_chains(chains)?;
1062        let mut query = Query::new();
1063        push_opt(&mut query, "period", period);
1064        push_list(&mut query, "blockchain", chains);
1065        push_list(&mut query, "tier", tiers);
1066        self.client.get("/calls/stats", query).await
1067    }
1068}
1069
1070/// Kept out of the public surface, but used by the type checker in tests.
1071#[allow(dead_code)]
1072fn _assert_send_sync() {
1073    fn assert<T: Send + Sync>() {}
1074    assert::<CabalSpy>();
1075    assert::<HashMap<String, serde_json::Value>>();
1076}
1077
1078#[cfg(test)]
1079mod tests {
1080    use super::*;
1081
1082    #[test]
1083    fn demo_constructor_uses_the_demo_key_and_normal_hosts() {
1084        let client = CabalSpy::builder()
1085            .demo()
1086            .base_url(DEFAULT_BASE_URL)
1087            .ws_url(DEFAULT_WS_URL)
1088            .build()
1089            .unwrap();
1090        assert!(client.is_demo());
1091        assert_eq!(client.base_url(), "https://api.cabalspy.xyz/v1");
1092        assert_eq!(
1093            client.websocket_url(),
1094            "wss://stream.cabalspy.xyz/?apiKey=demo"
1095        );
1096    }
1097
1098    #[test]
1099    fn token_query_carries_cursor_and_type() {
1100        let opts = TokenOpts {
1101            wallet_type: Some(WalletType::Kol),
1102            limit: Some(50),
1103            cursor: Some("c1".to_string()),
1104            since: Some("2026-11-04T00:00:00Z".to_string()),
1105        };
1106        let query = token_query(Chain::Solana, "m", &opts).unwrap();
1107        let get = |k: &str| query.iter().find(|(key, _)| key == k).map(|(_, v)| v.clone());
1108        assert_eq!(get("cursor").as_deref(), Some("c1"));
1109        assert_eq!(get("limit").as_deref(), Some("50"));
1110        assert_eq!(get("type").as_deref(), Some("kol"));
1111        assert_eq!(get("since"), None, "since is added by transactions_with only");
1112    }
1113
1114    #[test]
1115    fn demo_shortcut_is_a_demo_client() {
1116        assert!(CabalSpy::demo().unwrap().is_demo());
1117        assert!(!CabalSpy::new("sk_live_x").unwrap().is_demo());
1118        assert_eq!(DEMO_API_KEY, "demo");
1119    }
1120
1121    #[test]
1122    fn demo_envelope_is_parsed() {
1123        let raw = r#"{
1124            "success": true,
1125            "data": [{"wallet_address": "abc"}],
1126            "pagination": {"limit": 5, "has_more": false, "next_cursor": null},
1127            "meta": {"request_id": "r1"},
1128            "demo": {
1129                "notice": "Demo data, delayed 15 minutes.",
1130                "remaining_today": 17,
1131                "upgrade": {
1132                    "test_key": "https://apidashboard.cabalspy.xyz/",
1133                    "pay_per_call": "https://www.cabalspy.xyz/x402/",
1134                    "docs": "https://docs.cabalspy.xyz"
1135                }
1136            }
1137        }"#;
1138        let env: RawEnvelope<serde_json::Value> = serde_json::from_str(raw).unwrap();
1139        let pagination = env.pagination.unwrap();
1140        assert_eq!(pagination.limit, 5);
1141        assert!(!pagination.has_more);
1142        let info = demo_info(env.demo, Some(3)).unwrap();
1143        // The body wins over the header.
1144        assert_eq!(info.remaining_today, Some(17));
1145        assert_eq!(
1146            info.upgrade.unwrap().docs.as_deref(),
1147            Some("https://docs.cabalspy.xyz")
1148        );
1149    }
1150
1151    #[test]
1152    fn demo_info_falls_back_to_the_header() {
1153        assert_eq!(demo_info(None, Some(4)).unwrap().remaining_today, Some(4));
1154        assert!(demo_info(None, None).is_none());
1155        // A non-object `demo` value does not break anything.
1156        assert!(demo_info(Some(serde_json::json!(true)), None).is_none());
1157    }
1158}