Skip to main content

erpc_sdk/
price.rs

1use std::pin::Pin;
2
3use futures_util::{Stream, StreamExt};
4use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
5use serde::{Deserialize, Serialize};
6use tokio_util::sync::CancellationToken;
7
8use crate::{ErpcError, Result, rest::RestTransport, rpc::decode_json};
9
10/// Binary encoding requested from the price API.
11#[derive(Clone, Copy, Debug, Eq, PartialEq)]
12pub enum PriceEncoding {
13    /// Base64 text.
14    Base64,
15    /// Hexadecimal text.
16    Hex,
17}
18
19impl PriceEncoding {
20    const fn as_str(self) -> &'static str {
21        match self {
22            Self::Base64 => "base64",
23            Self::Hex => "hex",
24        }
25    }
26}
27
28/// Asset category used to filter feed metadata.
29#[derive(Clone, Copy, Debug, Eq, PartialEq)]
30pub enum PriceAssetType {
31    /// Crypto asset.
32    Crypto,
33    /// Equity.
34    Equity,
35    /// Foreign-exchange pair.
36    Fx,
37    /// Metal.
38    Metal,
39    /// Rates instrument.
40    Rates,
41}
42
43impl PriceAssetType {
44    const fn as_str(self) -> &'static str {
45        match self {
46            Self::Crypto => "crypto",
47            Self::Equity => "equity",
48            Self::Fx => "fx",
49            Self::Metal => "metal",
50            Self::Rates => "rates",
51        }
52    }
53}
54
55/// Price feed identifier and optional attributes.
56#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
57pub struct PriceFeedMetadata {
58    /// Optional feed attributes.
59    pub attributes: Option<std::collections::HashMap<String, String>>,
60    /// Feed identifier.
61    pub id: String,
62}
63
64/// One published price point.
65#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
66pub struct PricePoint {
67    /// Confidence interval as an integer string.
68    pub conf: String,
69    /// Decimal exponent.
70    pub expo: i32,
71    /// Price as an integer string.
72    pub price: String,
73    /// Unix publication time.
74    pub publish_time: i64,
75}
76
77/// Optional timing and slot metadata.
78#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
79pub struct ParsedPriceMetadata {
80    /// Previous publication time.
81    pub prev_publish_time: Option<i64>,
82    /// Proof availability time.
83    pub proof_available_time: Option<i64>,
84    /// Source slot.
85    pub slot: Option<u64>,
86}
87
88/// Parsed update for one feed.
89#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
90pub struct ParsedPriceUpdate {
91    /// Exponentially weighted moving-average price.
92    pub ema_price: PricePoint,
93    /// Feed identifier.
94    pub id: String,
95    /// Optional update metadata.
96    pub metadata: Option<ParsedPriceMetadata>,
97    /// Spot price.
98    pub price: PricePoint,
99}
100
101/// Binary price update payload.
102#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
103pub struct BinaryUpdate {
104    /// Encoded update values.
105    pub data: Vec<String>,
106    /// Encoding returned by the service.
107    pub encoding: String,
108}
109
110/// Latest or historical price updates.
111#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
112pub struct PriceUpdateResponse {
113    /// Binary updates.
114    pub binary: BinaryUpdate,
115    /// Parsed updates when requested.
116    pub parsed: Option<Vec<ParsedPriceUpdate>>,
117}
118
119/// Options shared by latest, historical, and streaming price updates.
120#[derive(Clone, Debug, Default, Eq, PartialEq)]
121pub struct PriceUpdateOptions {
122    /// Requested binary encoding.
123    pub encoding: Option<PriceEncoding>,
124    /// Feed identifiers. Repeated `ids[]` query keys are preserved.
125    pub ids: Vec<String>,
126    /// Ignore unrecognized feed identifiers.
127    pub ignore_invalid_price_ids: Option<bool>,
128    /// Include parsed values.
129    pub parsed: Option<bool>,
130}
131
132/// Options for the server-sent-events price stream.
133#[derive(Clone, Debug, Default, Eq, PartialEq)]
134pub struct PriceStreamOptions {
135    /// Shared update options.
136    pub update: PriceUpdateOptions,
137    /// Allow messages to arrive out of order.
138    pub allow_unordered: Option<bool>,
139    /// Return benchmark feeds only.
140    pub benchmarks_only: Option<bool>,
141}
142
143/// One publisher and its stake cap.
144#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
145pub struct PublisherStakeCap {
146    /// Stake cap.
147    pub cap: f64,
148    /// Publisher identifier.
149    pub publisher: String,
150}
151
152/// Parsed publisher stake cap envelope.
153#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
154pub struct ParsedPublisherStakeCaps {
155    /// Publisher stake caps.
156    pub publisher_stake_caps: Vec<PublisherStakeCap>,
157}
158
159/// Latest publisher stake caps.
160#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
161pub struct PublisherStakeCapsResponse {
162    /// Binary response.
163    pub binary: BinaryUpdate,
164    /// Parsed response when requested.
165    pub parsed: Option<Vec<ParsedPublisherStakeCaps>>,
166}
167
168/// Parsed server-sent event from the price stream.
169#[derive(Clone, Debug, PartialEq)]
170pub struct PriceStreamEvent {
171    /// Price update carried by `data` lines.
172    pub data: PriceUpdateResponse,
173    /// Optional SSE event name.
174    pub event: Option<String>,
175    /// Optional SSE event identifier.
176    pub id: Option<String>,
177}
178
179/// Boxed asynchronous stream returned by [`PriceClient::stream_price_updates`].
180pub type PriceStream = Pin<Box<dyn Stream<Item = Result<PriceStreamEvent>> + Send>>;
181
182/// Price metadata, updates, publisher caps, and streaming API.
183#[derive(Clone)]
184pub struct PriceClient {
185    transport: RestTransport,
186}
187
188impl PriceClient {
189    pub(crate) const fn new(transport: RestTransport) -> Self {
190        Self { transport }
191    }
192
193    /// Searches price feed metadata.
194    pub async fn get_price_feeds(
195        &self,
196        query_text: Option<&str>,
197        asset_type: Option<PriceAssetType>,
198    ) -> Result<Vec<PriceFeedMetadata>> {
199        self.get_price_feeds_with(query_text, asset_type, None)
200            .await
201    }
202
203    /// Searches price feed metadata with cancellation.
204    pub async fn get_price_feeds_with(
205        &self,
206        query_text: Option<&str>,
207        asset_type: Option<PriceAssetType>,
208        cancellation: Option<&CancellationToken>,
209    ) -> Result<Vec<PriceFeedMetadata>> {
210        let mut query = Vec::new();
211        if let Some(value) = query_text {
212            query.push(("query".to_owned(), value.to_owned()));
213        }
214        if let Some(value) = asset_type {
215            query.push(("asset_type".to_owned(), value.as_str().to_owned()));
216        }
217        self.transport
218            .get("/v2/price_feeds", query, cancellation)
219            .await
220    }
221
222    /// Gets latest price updates.
223    pub async fn get_latest_price_updates(
224        &self,
225        options: &PriceUpdateOptions,
226    ) -> Result<PriceUpdateResponse> {
227        self.get_latest_price_updates_with(options, None).await
228    }
229
230    /// Gets latest price updates with cancellation.
231    pub async fn get_latest_price_updates_with(
232        &self,
233        options: &PriceUpdateOptions,
234        cancellation: Option<&CancellationToken>,
235    ) -> Result<PriceUpdateResponse> {
236        self.transport
237            .get(
238                "/v2/updates/price/latest",
239                update_query(options),
240                cancellation,
241            )
242            .await
243    }
244
245    /// Gets price updates at a Unix publication time.
246    pub async fn get_price_updates_at_timestamp(
247        &self,
248        publish_time: impl std::fmt::Display,
249        options: &PriceUpdateOptions,
250    ) -> Result<PriceUpdateResponse> {
251        self.get_price_updates_at_timestamp_with(publish_time, options, None)
252            .await
253    }
254
255    /// Gets price updates at a Unix publication time with cancellation.
256    pub async fn get_price_updates_at_timestamp_with(
257        &self,
258        publish_time: impl std::fmt::Display,
259        options: &PriceUpdateOptions,
260        cancellation: Option<&CancellationToken>,
261    ) -> Result<PriceUpdateResponse> {
262        let publish_time = publish_time.to_string();
263        let segment = utf8_percent_encode(&publish_time, NON_ALPHANUMERIC);
264        let path = format!("/v2/updates/price/{segment}");
265        self.transport
266            .get(&path, update_query(options), cancellation)
267            .await
268    }
269
270    /// Gets latest publisher stake caps.
271    pub async fn get_latest_publisher_stake_caps(
272        &self,
273        encoding: Option<PriceEncoding>,
274        parsed: Option<bool>,
275    ) -> Result<PublisherStakeCapsResponse> {
276        self.get_latest_publisher_stake_caps_with(encoding, parsed, None)
277            .await
278    }
279
280    /// Gets latest publisher stake caps with cancellation.
281    pub async fn get_latest_publisher_stake_caps_with(
282        &self,
283        encoding: Option<PriceEncoding>,
284        parsed: Option<bool>,
285        cancellation: Option<&CancellationToken>,
286    ) -> Result<PublisherStakeCapsResponse> {
287        let mut query = Vec::new();
288        if let Some(value) = encoding {
289            query.push(("encoding".to_owned(), value.as_str().to_owned()));
290        }
291        if let Some(value) = parsed {
292            query.push(("parsed".to_owned(), value.to_string()));
293        }
294        self.transport
295            .get(
296                "/v2/updates/publisher_stake_caps/latest",
297                query,
298                cancellation,
299            )
300            .await
301    }
302
303    /// Connects to the price server-sent-events stream.
304    pub async fn stream_price_updates(
305        &self,
306        options: &PriceStreamOptions,
307        cancellation: Option<CancellationToken>,
308    ) -> Result<PriceStream> {
309        let mut query = update_query(&options.update);
310        if let Some(value) = options.allow_unordered {
311            query.push(("allow_unordered".to_owned(), value.to_string()));
312        }
313        if let Some(value) = options.benchmarks_only {
314            query.push(("benchmarks_only".to_owned(), value.to_string()));
315        }
316        let response = self
317            .transport
318            .get_response("/v2/updates/price/stream", query, cancellation.as_ref())
319            .await?;
320        let mut bytes = response.bytes_stream();
321        let output = async_stream::stream! {
322            let mut buffer = String::new();
323            loop {
324                let next = if let Some(token) = &cancellation {
325                    tokio::select! {
326                        () = token.cancelled() => {
327                            yield Err(ErpcError::Aborted);
328                            break;
329                        }
330                        next = bytes.next() => next,
331                    }
332                } else {
333                    bytes.next().await
334                };
335                let Some(chunk) = next else { break };
336                if let Ok(chunk) = chunk {
337                    buffer.push_str(&String::from_utf8_lossy(&chunk));
338                } else {
339                    yield Err(ErpcError::Transport("Unable to read ERPC stream".to_owned()));
340                    break;
341                }
342                while let Some((boundary, separator_length)) = sse_boundary(&buffer) {
343                    let block = buffer[..boundary].to_owned();
344                    buffer.drain(..boundary + separator_length);
345                    match parse_sse_block(&block) {
346                        Ok(Some(event)) => yield Ok(event),
347                        Ok(None) => {}
348                        Err(error) => {
349                            yield Err(error);
350                            return;
351                        }
352                    }
353                }
354            }
355            if !buffer.is_empty() {
356                match parse_sse_block(&buffer) {
357                    Ok(Some(event)) => yield Ok(event),
358                    Ok(None) => {}
359                    Err(error) => yield Err(error),
360                }
361            }
362        };
363        Ok(Box::pin(output))
364    }
365}
366
367fn update_query(options: &PriceUpdateOptions) -> Vec<(String, String)> {
368    let mut query: Vec<_> = options
369        .ids
370        .iter()
371        .map(|id| ("ids[]".to_owned(), id.clone()))
372        .collect();
373    if let Some(value) = options.encoding {
374        query.push(("encoding".to_owned(), value.as_str().to_owned()));
375    }
376    if let Some(value) = options.parsed {
377        query.push(("parsed".to_owned(), value.to_string()));
378    }
379    if let Some(value) = options.ignore_invalid_price_ids {
380        query.push(("ignore_invalid_price_ids".to_owned(), value.to_string()));
381    }
382    query
383}
384
385fn sse_boundary(buffer: &str) -> Option<(usize, usize)> {
386    match (buffer.find("\n\n"), buffer.find("\r\n\r\n")) {
387        (Some(left), Some(right)) if left <= right => Some((left, 2)),
388        (Some(_) | None, Some(right)) => Some((right, 4)),
389        (Some(left), None) => Some((left, 2)),
390        (None, None) => None,
391    }
392}
393
394fn parse_sse_block(block: &str) -> Result<Option<PriceStreamEvent>> {
395    let mut data = Vec::new();
396    let mut event = None;
397    let mut id = None;
398    for line in block.lines() {
399        if line.is_empty() || line.starts_with(':') {
400            continue;
401        }
402        let (field, raw) = line.split_once(':').unwrap_or((line, ""));
403        let value = raw.strip_prefix(' ').unwrap_or(raw);
404        match field {
405            "data" => data.push(value),
406            "event" => event = Some(value.to_owned()),
407            "id" => id = Some(value.to_owned()),
408            _ => {}
409        }
410    }
411    if data.is_empty() {
412        return Ok(None);
413    }
414    let response = decode_json(&data.join("\n")).map_err(|_| {
415        ErpcError::InvalidResponse("ERPC returned malformed stream data".to_owned())
416    })?;
417    Ok(Some(PriceStreamEvent {
418        data: response,
419        event,
420        id,
421    }))
422}