Skip to main content

erpc_sdk/
usage.rs

1use serde::{Deserialize, Serialize};
2use tokio_util::sync::CancellationToken;
3
4use crate::{ErpcError, Result, rest::RestTransport};
5
6/// Usage for one method within a chain.
7#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
8#[serde(rename_all = "camelCase")]
9pub struct MonthlyApiKeyMethodUsage {
10    /// Request count.
11    pub count: f64,
12    /// Credits charged per request.
13    pub credit_cost: f64,
14    /// Total credits charged.
15    pub credits: f64,
16    /// Wire-compatible RPC method.
17    pub method: String,
18    /// Last aggregation update.
19    pub updated_at: Option<String>,
20}
21
22/// Monthly usage aggregated by chain.
23#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
24#[serde(rename_all = "camelCase")]
25pub struct MonthlyApiKeyChainUsage {
26    /// Chain name.
27    pub chain: String,
28    /// Request count.
29    pub count: f64,
30    /// Total credits charged.
31    pub credits: f64,
32    /// Per-method usage.
33    pub methods: Vec<MonthlyApiKeyMethodUsage>,
34    /// Last aggregation update.
35    pub updated_at: Option<String>,
36}
37
38/// Credential-safe usage for one API key.
39#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
40#[serde(rename_all = "camelCase")]
41pub struct MonthlyApiKeyUsageEntry {
42    /// Last four characters only.
43    pub api_key_last4: String,
44    /// Total API key length.
45    pub api_key_length: f64,
46    /// Per-chain usage.
47    pub chains: Vec<MonthlyApiKeyChainUsage>,
48    /// Request count.
49    pub count: f64,
50    /// Total credits charged.
51    pub credits: f64,
52    /// Internal public key identifier when available.
53    pub key_id: Option<f64>,
54    /// Last aggregation update.
55    pub updated_at: Option<String>,
56}
57
58/// Monthly API key usage response.
59#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
60#[serde(rename_all = "camelCase")]
61pub struct MonthlyApiKeyUsage {
62    /// Usage grouped by API key.
63    pub api_keys: Vec<MonthlyApiKeyUsageEntry>,
64    /// Usage grouped by chain.
65    pub chains: Vec<MonthlyApiKeyChainUsage>,
66    /// Whether usage exists without a currently known key.
67    pub has_stranded_usage: bool,
68    /// Number of keys.
69    pub key_count: f64,
70    /// Total request count.
71    pub total_count: f64,
72    /// Total credits charged.
73    pub total_credits: f64,
74    /// Last aggregation update.
75    pub updated_at: Option<String>,
76    /// Calendar month in `YYYY-MM` form.
77    pub year_month: String,
78}
79
80/// Parameters for monthly usage retrieval.
81#[derive(Clone, Debug, Default, Eq, PartialEq)]
82pub struct MonthlyApiKeyUsageParams {
83    /// Calendar month in `YYYY-MM` form. Current month when omitted.
84    pub year_month: Option<String>,
85}
86
87/// Monthly usage API.
88#[derive(Clone)]
89pub struct UsageClient {
90    transport: RestTransport,
91}
92
93impl UsageClient {
94    pub(crate) const fn new(transport: RestTransport) -> Self {
95        Self { transport }
96    }
97
98    /// Gets monthly API key usage.
99    pub async fn get_monthly_api_key_usage(
100        &self,
101        params: MonthlyApiKeyUsageParams,
102    ) -> Result<MonthlyApiKeyUsage> {
103        self.get_monthly_api_key_usage_with(params, None).await
104    }
105
106    /// Gets monthly API key usage with cancellation.
107    pub async fn get_monthly_api_key_usage_with(
108        &self,
109        params: MonthlyApiKeyUsageParams,
110        cancellation: Option<&CancellationToken>,
111    ) -> Result<MonthlyApiKeyUsage> {
112        if let Some(year_month) = &params.year_month {
113            if !valid_year_month(year_month) {
114                return Err(ErpcError::Config(
115                    "year_month must use YYYY-MM format".to_owned(),
116                ));
117            }
118        }
119        let query = params
120            .year_month
121            .map(|value| vec![("yearMonth".to_owned(), value)])
122            .unwrap_or_default();
123        let envelope: Envelope<MonthlyApiKeyUsage> = self
124            .transport
125            .get("/v3/user/api-keys/usage", query, cancellation)
126            .await?;
127        if !envelope.success || !valid_year_month(&envelope.message.year_month) {
128            return Err(ErpcError::InvalidResponse(
129                "ERPC returned an invalid monthly API key usage response".to_owned(),
130            ));
131        }
132        Ok(envelope.message)
133    }
134}
135
136#[derive(Deserialize)]
137struct Envelope<T> {
138    success: bool,
139    message: T,
140}
141
142fn valid_year_month(value: &str) -> bool {
143    let bytes = value.as_bytes();
144    bytes.len() == 7
145        && bytes[0..4].iter().all(u8::is_ascii_digit)
146        && bytes[4] == b'-'
147        && matches!(
148            &bytes[5..7],
149            b"01"
150                | b"02"
151                | b"03"
152                | b"04"
153                | b"05"
154                | b"06"
155                | b"07"
156                | b"08"
157                | b"09"
158                | b"10"
159                | b"11"
160                | b"12"
161        )
162}