Skip to main content

af_price_updates/
stork.rs

1//! Stork price update data, asset identifiers, and BCS serialization helpers.
2
3use crate::{ParseError, U256, keccak::keccak256};
4use bytes::{BufMut, BytesMut};
5use serde::{Deserialize, Serialize};
6use std::array::TryFromSliceError;
7
8pub use crate::stork_small_id::SmallAssetId;
9
10/// An asset id as used by Stork, e.g. "BTCUSD" or "ETHUSD".
11///
12/// List of available asset ids and their encodings can be found at
13/// <https://docs.stork.network/resources/asset-id-registry>
14pub type AssetId = String;
15
16/// Keccak256-encoded asset id, as used in Stork price updates.
17///
18/// For example, "BTCUSD" is encoded as
19/// 0x7404e3d104ea7841c3d9e6fd20adfe99b4ad586bc08d8f3bd3afef894cf184de. Displayed, parsed and
20/// serialized like its [`U256`].
21///
22/// List of available asset ids and their encodings can be found at
23/// <https://docs.stork.network/resources/asset-id-registry>
24#[derive(
25    Clone, Copy, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize,
26)]
27#[repr(transparent)]
28pub struct EncodedAssetId(pub U256);
29
30impl EncodedAssetId {
31    /// Derives the Keccak256-encoded asset id from a regular asset id string.
32    pub fn from_asset_id<S: AsRef<str>>(asset_id: S) -> Self {
33        Self(U256::from(keccak256(asset_id.as_ref().as_bytes())))
34    }
35    /// The 32 bytes, e.g. for the on-chain Stork `EncodedAssetId`.
36    pub const fn as_slice(&self) -> &[u8] {
37        self.0.as_slice()
38    }
39}
40
41impl From<[u8; 32]> for EncodedAssetId {
42    fn from(bytes: [u8; 32]) -> Self {
43        Self(U256::from(bytes))
44    }
45}
46
47impl AsRef<[u8]> for EncodedAssetId {
48    fn as_ref(&self) -> &[u8] {
49        self.as_slice()
50    }
51}
52
53impl TryFrom<&[u8]> for EncodedAssetId {
54    type Error = TryFromSliceError;
55    /// Takes exactly 32 bytes, e.g. those of the on-chain Stork `EncodedAssetId`.
56    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
57        U256::try_from(bytes).map(Self)
58    }
59}
60
61impl std::fmt::Display for EncodedAssetId {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        <U256 as std::fmt::Display>::fmt(&self.0, f)
64    }
65}
66
67impl std::str::FromStr for EncodedAssetId {
68    type Err = ParseError;
69    fn from_str(s: &str) -> Result<Self, Self::Err> {
70        s.parse::<U256>().map(Self)
71    }
72}
73
74/// A signed Stork price update for one asset, with the fields the on-chain Stork contract needs to
75/// verify it.
76///
77/// This flattens the `stork_signed_price` of a Stork API price message; its serde and BCS forms
78/// are this crate's own, not the Stork API's JSON. See
79/// <https://docs.stork.network/getting-started/becoming-a-subscriber> for the API.
80#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
81pub struct PriceUpdate {
82    /// Keccak256-encoded asset id.
83    pub id: EncodedAssetId,
84    /// Unix timestamp in nanoseconds.
85    pub timestamp_ns: u64,
86    /// Price multiplied by 10^18.
87    pub quantized_value_magnitude: u128,
88    /// Sign of the price.
89    pub quantized_value_negative: bool,
90    /// Publisher merkle root. Needed for on-chain verification.
91    pub publisher_merkle_root: U256,
92    /// Checksum for aggregation function. Needed for on-chain verification.
93    pub value_compute_alg_hash: U256,
94    /// r component of ECDSA secp256k1 signature. Needed for on-chain verification.
95    pub r: U256,
96    /// s component of ECDSA secp256k1 signature. Needed for on-chain verification.
97    pub s: U256,
98    /// v component of ECDSA secp256k1 signature. Needed for on-chain verification.
99    pub v: u8,
100}
101
102impl TryFrom<BytesMut> for PriceUpdate {
103    type Error = std::io::Error;
104    /// Decodes the BCS representation, like [`PriceUpdate::from_slice`].
105    fn try_from(bytes: BytesMut) -> Result<Self, Self::Error> {
106        Self::from_slice(&bytes)
107    }
108}
109
110impl PriceUpdate {
111    /// Decodes the BCS representation written by [`Self::serialize_into`].
112    pub fn from_slice(bytes: &[u8]) -> Result<Self, std::io::Error> {
113        bcs::from_bytes(bytes)
114            .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))
115    }
116    /// Length of the BCS representation.
117    pub fn serialized_size(&self) -> usize {
118        bcs::serialized_size(self).expect("BCS-serializable")
119    }
120    /// Writes the BCS representation, [`Self::serialized_size`] bytes long.
121    pub fn serialize_into<W: BufMut>(&self, w: &mut W) {
122        let mut writer = w.writer();
123        bcs::serialize_into(&mut writer, self).expect("BCS-serializable");
124    }
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130
131    #[test]
132    fn stork_encoded_asset_id() {
133        assert_eq!(
134            EncodedAssetId::from_asset_id("BTCUSD"),
135            EncodedAssetId(U256::strict_from_str(
136                "0x7404e3d104ea7841c3d9e6fd20adfe99b4ad586bc08d8f3bd3afef894cf184de"
137            )),
138        );
139        assert_eq!(
140            EncodedAssetId::from_asset_id("ETHUSD"),
141            EncodedAssetId(U256::strict_from_str(
142                "0x59102b37de83bdda9f38ac8254e596f0d9ac61d2035c07936675e87342817160"
143            )),
144        );
145    }
146
147    #[test]
148    fn stork_bytes_serde() {
149        let asset_id = SmallAssetId::intern("BTCUSD");
150        let update = PriceUpdate {
151            id: EncodedAssetId::from_asset_id(asset_id),
152            timestamp_ns: 1_234_567_890,
153            quantized_value_magnitude: 12_345_678_901_234_567_890,
154            quantized_value_negative: true,
155            publisher_merkle_root: U256::from(42),
156            value_compute_alg_hash: U256::from(43),
157            r: U256::from(44),
158            s: U256::from(45),
159            v: 27,
160        };
161        let mut bytes = BytesMut::with_capacity(update.serialized_size());
162        update.serialize_into(&mut bytes);
163        assert_eq!(bytes.len(), update.serialized_size());
164        assert_eq!(PriceUpdate::from_slice(&bytes).unwrap(), update);
165        let deserialized = PriceUpdate::try_from(bytes).unwrap();
166        assert_eq!(update, deserialized);
167    }
168
169    #[test]
170    fn encoded_asset_id_from_bytes() {
171        let id = EncodedAssetId::from_asset_id("BTCUSD");
172
173        assert_eq!(EncodedAssetId::try_from(id.as_slice()).unwrap(), id);
174        assert_eq!(EncodedAssetId::from(id.0.into_inner()), id);
175        assert_eq!(id.as_ref(), id.0.as_slice());
176        assert!(EncodedAssetId::try_from(&id.0.as_slice()[1..]).is_err());
177        assert!(EncodedAssetId::try_from([0; 33].as_slice()).is_err());
178    }
179
180    #[test]
181    fn encoded_asset_id_formats_like_u256() {
182        let id = EncodedAssetId::from_asset_id("BTCUSD");
183        let hex = "0x7404e3d104ea7841c3d9e6fd20adfe99b4ad586bc08d8f3bd3afef894cf184de";
184
185        assert_eq!(id.to_string(), hex);
186        assert_eq!(hex.parse(), Ok(id));
187        assert_eq!(serde_json::to_string(&id).unwrap(), format!("\"{hex}\""));
188        assert_eq!(
189            serde_json::from_str::<EncodedAssetId>(&format!("\"{hex}\"")).unwrap(),
190            id
191        );
192        assert_eq!(bcs::to_bytes(&id).unwrap(), bcs::to_bytes(&id.0).unwrap());
193    }
194}