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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
12pub enum PriceEncoding {
13 Base64,
15 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
30pub enum PriceAssetType {
31 Crypto,
33 Equity,
35 Fx,
37 Metal,
39 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#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
57pub struct PriceFeedMetadata {
58 pub attributes: Option<std::collections::HashMap<String, String>>,
60 pub id: String,
62}
63
64#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
66pub struct PricePoint {
67 pub conf: String,
69 pub expo: i32,
71 pub price: String,
73 pub publish_time: i64,
75}
76
77#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
79pub struct ParsedPriceMetadata {
80 pub prev_publish_time: Option<i64>,
82 pub proof_available_time: Option<i64>,
84 pub slot: Option<u64>,
86}
87
88#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
90pub struct ParsedPriceUpdate {
91 pub ema_price: PricePoint,
93 pub id: String,
95 pub metadata: Option<ParsedPriceMetadata>,
97 pub price: PricePoint,
99}
100
101#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
103pub struct BinaryUpdate {
104 pub data: Vec<String>,
106 pub encoding: String,
108}
109
110#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
112pub struct PriceUpdateResponse {
113 pub binary: BinaryUpdate,
115 pub parsed: Option<Vec<ParsedPriceUpdate>>,
117}
118
119#[derive(Clone, Debug, Default, Eq, PartialEq)]
121pub struct PriceUpdateOptions {
122 pub encoding: Option<PriceEncoding>,
124 pub ids: Vec<String>,
126 pub ignore_invalid_price_ids: Option<bool>,
128 pub parsed: Option<bool>,
130}
131
132#[derive(Clone, Debug, Default, Eq, PartialEq)]
134pub struct PriceStreamOptions {
135 pub update: PriceUpdateOptions,
137 pub allow_unordered: Option<bool>,
139 pub benchmarks_only: Option<bool>,
141}
142
143#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
145pub struct PublisherStakeCap {
146 pub cap: f64,
148 pub publisher: String,
150}
151
152#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
154pub struct ParsedPublisherStakeCaps {
155 pub publisher_stake_caps: Vec<PublisherStakeCap>,
157}
158
159#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
161pub struct PublisherStakeCapsResponse {
162 pub binary: BinaryUpdate,
164 pub parsed: Option<Vec<ParsedPublisherStakeCaps>>,
166}
167
168#[derive(Clone, Debug, PartialEq)]
170pub struct PriceStreamEvent {
171 pub data: PriceUpdateResponse,
173 pub event: Option<String>,
175 pub id: Option<String>,
177}
178
179pub type PriceStream = Pin<Box<dyn Stream<Item = Result<PriceStreamEvent>> + Send>>;
181
182#[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 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 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 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 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 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 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 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 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 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}