router.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. //! WebSocket JSON protocol types for the API the router provides to consumers and publishers.
  2. use {
  3. crate::{
  4. payload::AggregatedPriceFeedData,
  5. time::{DurationUs, TimestampUs},
  6. },
  7. anyhow::{bail, Context},
  8. derive_more::derive::{From, Into},
  9. itertools::Itertools,
  10. protobuf::well_known_types::duration::Duration as ProtobufDuration,
  11. rust_decimal::{prelude::FromPrimitive, Decimal},
  12. serde::{de::Error, Deserialize, Serialize},
  13. std::{
  14. cmp::Ordering,
  15. fmt::Display,
  16. num::NonZeroI64,
  17. ops::{Add, Deref, DerefMut, Div, Sub},
  18. },
  19. };
  20. #[derive(
  21. Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, From, Into,
  22. )]
  23. pub struct PublisherId(pub u16);
  24. #[derive(
  25. Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, From, Into,
  26. )]
  27. pub struct PriceFeedId(pub u32);
  28. #[derive(
  29. Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, From, Into,
  30. )]
  31. pub struct ChannelId(pub u8);
  32. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
  33. #[repr(transparent)]
  34. pub struct Rate(pub i64);
  35. impl Rate {
  36. pub fn parse_str(value: &str, exponent: u32) -> anyhow::Result<Self> {
  37. let value: Decimal = value.parse()?;
  38. let coef = 10i64.checked_pow(exponent).context("overflow")?;
  39. let coef = Decimal::from_i64(coef).context("overflow")?;
  40. let value = value.checked_mul(coef).context("overflow")?;
  41. if !value.is_integer() {
  42. bail!("price value is more precise than available exponent");
  43. }
  44. let value: i64 = value.try_into().context("overflow")?;
  45. Ok(Self(value))
  46. }
  47. pub fn from_f64(value: f64, exponent: u32) -> anyhow::Result<Self> {
  48. let value = Decimal::from_f64(value).context("overflow")?;
  49. let coef = 10i64.checked_pow(exponent).context("overflow")?;
  50. let coef = Decimal::from_i64(coef).context("overflow")?;
  51. let value = value.checked_mul(coef).context("overflow")?;
  52. let value: i64 = value.try_into().context("overflow")?;
  53. Ok(Self(value))
  54. }
  55. pub fn from_integer(value: i64, exponent: u32) -> anyhow::Result<Self> {
  56. let coef = 10i64.checked_pow(exponent).context("overflow")?;
  57. let value = value.checked_mul(coef).context("overflow")?;
  58. Ok(Self(value))
  59. }
  60. }
  61. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
  62. #[repr(transparent)]
  63. pub struct Price(pub NonZeroI64);
  64. impl Price {
  65. pub fn from_integer(value: i64, exponent: u32) -> anyhow::Result<Price> {
  66. let coef = 10i64.checked_pow(exponent).context("overflow")?;
  67. let value = value.checked_mul(coef).context("overflow")?;
  68. let value = NonZeroI64::new(value).context("zero price is unsupported")?;
  69. Ok(Self(value))
  70. }
  71. pub fn parse_str(value: &str, exponent: u32) -> anyhow::Result<Price> {
  72. let value: Decimal = value.parse()?;
  73. let coef = 10i64.checked_pow(exponent).context("overflow")?;
  74. let coef = Decimal::from_i64(coef).context("overflow")?;
  75. let value = value.checked_mul(coef).context("overflow")?;
  76. if !value.is_integer() {
  77. bail!("price value is more precise than available exponent");
  78. }
  79. let value: i64 = value.try_into().context("overflow")?;
  80. let value = NonZeroI64::new(value).context("zero price is unsupported")?;
  81. Ok(Self(value))
  82. }
  83. pub fn new(value: i64) -> anyhow::Result<Self> {
  84. let value = NonZeroI64::new(value).context("zero price is unsupported")?;
  85. Ok(Self(value))
  86. }
  87. pub fn into_inner(self) -> NonZeroI64 {
  88. self.0
  89. }
  90. pub fn to_f64(self, exponent: u32) -> anyhow::Result<f64> {
  91. Ok(self.0.get() as f64 / 10i64.checked_pow(exponent).context("overflow")? as f64)
  92. }
  93. pub fn from_f64(value: f64, exponent: u32) -> anyhow::Result<Self> {
  94. let value = (value * 10f64.powi(exponent as i32)) as i64;
  95. let value = NonZeroI64::new(value).context("zero price is unsupported")?;
  96. Ok(Self(value))
  97. }
  98. pub fn mul(self, rhs: Price, rhs_exponent: u32) -> anyhow::Result<Price> {
  99. let left_value = i128::from(self.0.get());
  100. let right_value = i128::from(rhs.0.get());
  101. let value = left_value * right_value / 10i128.pow(rhs_exponent);
  102. let value = value.try_into()?;
  103. NonZeroI64::new(value)
  104. .context("zero price is unsupported")
  105. .map(Self)
  106. }
  107. }
  108. impl Sub<i64> for Price {
  109. type Output = Option<Price>;
  110. fn sub(self, rhs: i64) -> Self::Output {
  111. let value = self.0.get().saturating_sub(rhs);
  112. NonZeroI64::new(value).map(Self)
  113. }
  114. }
  115. impl Add<i64> for Price {
  116. type Output = Option<Price>;
  117. fn add(self, rhs: i64) -> Self::Output {
  118. let value = self.0.get().saturating_add(rhs);
  119. NonZeroI64::new(value).map(Self)
  120. }
  121. }
  122. impl Add<Price> for Price {
  123. type Output = Option<Price>;
  124. fn add(self, rhs: Price) -> Self::Output {
  125. let value = self.0.get().saturating_add(rhs.0.get());
  126. NonZeroI64::new(value).map(Self)
  127. }
  128. }
  129. impl Sub<Price> for Price {
  130. type Output = Option<Price>;
  131. fn sub(self, rhs: Price) -> Self::Output {
  132. let value = self.0.get().saturating_sub(rhs.0.get());
  133. NonZeroI64::new(value).map(Self)
  134. }
  135. }
  136. impl Div<i64> for Price {
  137. type Output = Option<Price>;
  138. fn div(self, rhs: i64) -> Self::Output {
  139. let value = self.0.get().saturating_div(rhs);
  140. NonZeroI64::new(value).map(Self)
  141. }
  142. }
  143. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
  144. #[serde(rename_all = "camelCase")]
  145. pub enum PriceFeedProperty {
  146. Price,
  147. BestBidPrice,
  148. BestAskPrice,
  149. PublisherCount,
  150. Exponent,
  151. Confidence,
  152. FundingRate,
  153. FundingTimestamp,
  154. FundingRateInterval,
  155. // More fields may be added later.
  156. }
  157. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
  158. #[serde(rename_all = "camelCase")]
  159. pub enum DeliveryFormat {
  160. /// Deliver stream updates as JSON text messages.
  161. #[default]
  162. Json,
  163. /// Deliver stream updates as binary messages.
  164. Binary,
  165. }
  166. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
  167. #[serde(rename_all = "camelCase")]
  168. pub enum Format {
  169. Evm,
  170. Solana,
  171. LeEcdsa,
  172. LeUnsigned,
  173. }
  174. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
  175. #[serde(rename_all = "camelCase")]
  176. pub enum JsonBinaryEncoding {
  177. #[default]
  178. Base64,
  179. Hex,
  180. }
  181. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, From)]
  182. pub enum Channel {
  183. FixedRate(FixedRate),
  184. RealTime,
  185. }
  186. impl PartialOrd for Channel {
  187. fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
  188. let rate_left = match self {
  189. Channel::FixedRate(rate) => rate.duration().as_micros(),
  190. Channel::RealTime => FixedRate::MIN.duration().as_micros(),
  191. };
  192. let rate_right = match other {
  193. Channel::FixedRate(rate) => rate.duration().as_micros(),
  194. Channel::RealTime => FixedRate::MIN.duration().as_micros(),
  195. };
  196. Some(rate_left.cmp(&rate_right))
  197. }
  198. }
  199. impl Serialize for Channel {
  200. fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  201. where
  202. S: serde::Serializer,
  203. {
  204. match self {
  205. Channel::FixedRate(fixed_rate) => serializer.serialize_str(&format!(
  206. "fixed_rate@{}ms",
  207. fixed_rate.duration().as_millis()
  208. )),
  209. Channel::RealTime => serializer.serialize_str("real_time"),
  210. }
  211. }
  212. }
  213. pub mod channel_ids {
  214. use super::ChannelId;
  215. pub const REAL_TIME: ChannelId = ChannelId(1);
  216. pub const FIXED_RATE_50: ChannelId = ChannelId(2);
  217. pub const FIXED_RATE_200: ChannelId = ChannelId(3);
  218. }
  219. impl Display for Channel {
  220. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  221. match self {
  222. Channel::FixedRate(fixed_rate) => {
  223. write!(f, "fixed_rate@{}ms", fixed_rate.duration().as_millis())
  224. }
  225. Channel::RealTime => write!(f, "real_time"),
  226. }
  227. }
  228. }
  229. impl Channel {
  230. pub fn id(&self) -> ChannelId {
  231. match self {
  232. Channel::FixedRate(fixed_rate) => match fixed_rate.duration().as_millis() {
  233. 50 => channel_ids::FIXED_RATE_50,
  234. 200 => channel_ids::FIXED_RATE_200,
  235. _ => panic!("unknown channel: {self:?}"),
  236. },
  237. Channel::RealTime => channel_ids::REAL_TIME,
  238. }
  239. }
  240. }
  241. #[test]
  242. fn id_supports_all_fixed_rates() {
  243. for rate in FixedRate::ALL {
  244. Channel::FixedRate(rate).id();
  245. }
  246. }
  247. fn parse_channel(value: &str) -> Option<Channel> {
  248. if value == "real_time" {
  249. Some(Channel::RealTime)
  250. } else if let Some(rest) = value.strip_prefix("fixed_rate@") {
  251. let ms_value = rest.strip_suffix("ms")?;
  252. Some(Channel::FixedRate(FixedRate::from_millis(
  253. ms_value.parse().ok()?,
  254. )?))
  255. } else {
  256. None
  257. }
  258. }
  259. impl<'de> Deserialize<'de> for Channel {
  260. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  261. where
  262. D: serde::Deserializer<'de>,
  263. {
  264. let value = <String>::deserialize(deserializer)?;
  265. parse_channel(&value).ok_or_else(|| Error::custom("unknown channel"))
  266. }
  267. }
  268. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
  269. pub struct FixedRate {
  270. rate: DurationUs,
  271. }
  272. impl FixedRate {
  273. pub const RATE_50_MS: Self = Self {
  274. rate: DurationUs::from_millis_u32(50),
  275. };
  276. pub const RATE_200_MS: Self = Self {
  277. rate: DurationUs::from_millis_u32(200),
  278. };
  279. // Assumptions (tested below):
  280. // - Values are sorted.
  281. // - 1 second contains a whole number of each interval.
  282. // - all intervals are divisable by the smallest interval.
  283. pub const ALL: [Self; 2] = [Self::RATE_50_MS, Self::RATE_200_MS];
  284. pub const MIN: Self = Self::ALL[0];
  285. pub fn from_millis(millis: u32) -> Option<Self> {
  286. Self::ALL
  287. .into_iter()
  288. .find(|v| v.rate.as_millis() == u64::from(millis))
  289. }
  290. pub fn duration(self) -> DurationUs {
  291. self.rate
  292. }
  293. }
  294. impl TryFrom<DurationUs> for FixedRate {
  295. type Error = anyhow::Error;
  296. fn try_from(value: DurationUs) -> Result<Self, Self::Error> {
  297. Self::ALL
  298. .into_iter()
  299. .find(|v| v.rate == value)
  300. .with_context(|| format!("unsupported rate: {value:?}"))
  301. }
  302. }
  303. impl TryFrom<&ProtobufDuration> for FixedRate {
  304. type Error = anyhow::Error;
  305. fn try_from(value: &ProtobufDuration) -> Result<Self, Self::Error> {
  306. let duration = DurationUs::try_from(value)?;
  307. Self::try_from(duration)
  308. }
  309. }
  310. impl TryFrom<ProtobufDuration> for FixedRate {
  311. type Error = anyhow::Error;
  312. fn try_from(duration: ProtobufDuration) -> anyhow::Result<Self> {
  313. TryFrom::<&ProtobufDuration>::try_from(&duration)
  314. }
  315. }
  316. impl From<FixedRate> for DurationUs {
  317. fn from(value: FixedRate) -> Self {
  318. value.rate
  319. }
  320. }
  321. impl From<FixedRate> for ProtobufDuration {
  322. fn from(value: FixedRate) -> Self {
  323. value.rate.into()
  324. }
  325. }
  326. #[test]
  327. fn fixed_rate_values() {
  328. assert!(
  329. FixedRate::ALL.windows(2).all(|w| w[0] < w[1]),
  330. "values must be unique and sorted"
  331. );
  332. for value in FixedRate::ALL {
  333. assert_eq!(
  334. 1_000_000 % value.duration().as_micros(),
  335. 0,
  336. "1 s must contain whole number of intervals"
  337. );
  338. assert_eq!(
  339. value.duration().as_micros() % FixedRate::MIN.duration().as_micros(),
  340. 0,
  341. "the interval's borders must be a subset of the minimal interval's borders"
  342. );
  343. }
  344. }
  345. #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
  346. #[serde(rename_all = "camelCase")]
  347. pub struct SubscriptionParamsRepr {
  348. pub price_feed_ids: Vec<PriceFeedId>,
  349. pub properties: Vec<PriceFeedProperty>,
  350. // "chains" was renamed to "formats". "chains" is still supported for compatibility.
  351. #[serde(alias = "chains")]
  352. pub formats: Vec<Format>,
  353. #[serde(default)]
  354. pub delivery_format: DeliveryFormat,
  355. #[serde(default)]
  356. pub json_binary_encoding: JsonBinaryEncoding,
  357. /// If `true`, the stream update will contain a `parsed` JSON field containing
  358. /// all data of the update.
  359. #[serde(default = "default_parsed")]
  360. pub parsed: bool,
  361. pub channel: Channel,
  362. #[serde(default)]
  363. pub ignore_invalid_feed_ids: bool,
  364. }
  365. #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
  366. #[serde(rename_all = "camelCase")]
  367. pub struct SubscriptionParams(SubscriptionParamsRepr);
  368. impl<'de> Deserialize<'de> for SubscriptionParams {
  369. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  370. where
  371. D: serde::Deserializer<'de>,
  372. {
  373. let value = SubscriptionParamsRepr::deserialize(deserializer)?;
  374. Self::new(value).map_err(Error::custom)
  375. }
  376. }
  377. impl SubscriptionParams {
  378. pub fn new(value: SubscriptionParamsRepr) -> Result<Self, &'static str> {
  379. if value.price_feed_ids.is_empty() {
  380. return Err("no price feed ids specified");
  381. }
  382. if !value.price_feed_ids.iter().all_unique() {
  383. return Err("duplicate price feed ids specified");
  384. }
  385. if !value.formats.iter().all_unique() {
  386. return Err("duplicate formats or chains specified");
  387. }
  388. if value.properties.is_empty() {
  389. return Err("no properties specified");
  390. }
  391. if !value.properties.iter().all_unique() {
  392. return Err("duplicate properties specified");
  393. }
  394. Ok(Self(value))
  395. }
  396. }
  397. impl Deref for SubscriptionParams {
  398. type Target = SubscriptionParamsRepr;
  399. fn deref(&self) -> &Self::Target {
  400. &self.0
  401. }
  402. }
  403. impl DerefMut for SubscriptionParams {
  404. fn deref_mut(&mut self) -> &mut Self::Target {
  405. &mut self.0
  406. }
  407. }
  408. pub fn default_parsed() -> bool {
  409. true
  410. }
  411. #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
  412. #[serde(rename_all = "camelCase")]
  413. pub struct JsonBinaryData {
  414. pub encoding: JsonBinaryEncoding,
  415. pub data: String,
  416. }
  417. #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
  418. #[serde(rename_all = "camelCase")]
  419. pub struct JsonUpdate {
  420. /// Present unless `parsed = false` is specified in subscription params.
  421. #[serde(skip_serializing_if = "Option::is_none")]
  422. pub parsed: Option<ParsedPayload>,
  423. /// Only present if `Evm` is present in `formats` in subscription params.
  424. #[serde(skip_serializing_if = "Option::is_none")]
  425. pub evm: Option<JsonBinaryData>,
  426. /// Only present if `Solana` is present in `formats` in subscription params.
  427. #[serde(skip_serializing_if = "Option::is_none")]
  428. pub solana: Option<JsonBinaryData>,
  429. /// Only present if `LeEcdsa` is present in `formats` in subscription params.
  430. #[serde(skip_serializing_if = "Option::is_none")]
  431. pub le_ecdsa: Option<JsonBinaryData>,
  432. /// Only present if `LeUnsigned` is present in `formats` in subscription params.
  433. #[serde(skip_serializing_if = "Option::is_none")]
  434. pub le_unsigned: Option<JsonBinaryData>,
  435. }
  436. #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
  437. #[serde(rename_all = "camelCase")]
  438. pub struct ParsedPayload {
  439. #[serde(with = "crate::serde_str::timestamp")]
  440. pub timestamp_us: TimestampUs,
  441. pub price_feeds: Vec<ParsedFeedPayload>,
  442. }
  443. #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
  444. #[serde(rename_all = "camelCase")]
  445. pub struct ParsedFeedPayload {
  446. pub price_feed_id: PriceFeedId,
  447. #[serde(skip_serializing_if = "Option::is_none")]
  448. #[serde(with = "crate::serde_str::option_price")]
  449. #[serde(default)]
  450. pub price: Option<Price>,
  451. #[serde(skip_serializing_if = "Option::is_none")]
  452. #[serde(with = "crate::serde_str::option_price")]
  453. #[serde(default)]
  454. pub best_bid_price: Option<Price>,
  455. #[serde(skip_serializing_if = "Option::is_none")]
  456. #[serde(with = "crate::serde_str::option_price")]
  457. #[serde(default)]
  458. pub best_ask_price: Option<Price>,
  459. #[serde(skip_serializing_if = "Option::is_none")]
  460. #[serde(default)]
  461. pub publisher_count: Option<u16>,
  462. #[serde(skip_serializing_if = "Option::is_none")]
  463. #[serde(default)]
  464. pub exponent: Option<i16>,
  465. #[serde(skip_serializing_if = "Option::is_none")]
  466. #[serde(default)]
  467. pub confidence: Option<Price>,
  468. #[serde(skip_serializing_if = "Option::is_none")]
  469. #[serde(default)]
  470. pub funding_rate: Option<Rate>,
  471. #[serde(skip_serializing_if = "Option::is_none")]
  472. #[serde(default)]
  473. pub funding_timestamp: Option<TimestampUs>,
  474. // More fields may be added later.
  475. #[serde(skip_serializing_if = "Option::is_none")]
  476. #[serde(default)]
  477. pub funding_rate_interval: Option<DurationUs>,
  478. }
  479. impl ParsedFeedPayload {
  480. pub fn new(
  481. price_feed_id: PriceFeedId,
  482. exponent: Option<i16>,
  483. data: &AggregatedPriceFeedData,
  484. properties: &[PriceFeedProperty],
  485. ) -> Self {
  486. let mut output = Self {
  487. price_feed_id,
  488. price: None,
  489. best_bid_price: None,
  490. best_ask_price: None,
  491. publisher_count: None,
  492. exponent: None,
  493. confidence: None,
  494. funding_rate: None,
  495. funding_timestamp: None,
  496. funding_rate_interval: None,
  497. };
  498. for &property in properties {
  499. match property {
  500. PriceFeedProperty::Price => {
  501. output.price = data.price;
  502. }
  503. PriceFeedProperty::BestBidPrice => {
  504. output.best_bid_price = data.best_bid_price;
  505. }
  506. PriceFeedProperty::BestAskPrice => {
  507. output.best_ask_price = data.best_ask_price;
  508. }
  509. PriceFeedProperty::PublisherCount => {
  510. output.publisher_count = Some(data.publisher_count);
  511. }
  512. PriceFeedProperty::Exponent => {
  513. output.exponent = exponent;
  514. }
  515. PriceFeedProperty::Confidence => {
  516. output.confidence = data.confidence;
  517. }
  518. PriceFeedProperty::FundingRate => {
  519. output.funding_rate = data.funding_rate;
  520. }
  521. PriceFeedProperty::FundingTimestamp => {
  522. output.funding_timestamp = data.funding_timestamp;
  523. }
  524. PriceFeedProperty::FundingRateInterval => {
  525. output.funding_rate_interval = data.funding_rate_interval;
  526. }
  527. }
  528. }
  529. output
  530. }
  531. pub fn new_full(
  532. price_feed_id: PriceFeedId,
  533. exponent: Option<i16>,
  534. data: &AggregatedPriceFeedData,
  535. ) -> Self {
  536. Self {
  537. price_feed_id,
  538. price: data.price,
  539. best_bid_price: data.best_bid_price,
  540. best_ask_price: data.best_ask_price,
  541. publisher_count: Some(data.publisher_count),
  542. exponent,
  543. confidence: data.confidence,
  544. funding_rate: data.funding_rate,
  545. funding_timestamp: data.funding_timestamp,
  546. funding_rate_interval: data.funding_rate_interval,
  547. }
  548. }
  549. }