|
| 1 | +use { |
| 2 | + crate::{ |
| 3 | + api::{ |
| 4 | + rest::{validate_price_ids, RestError}, |
| 5 | + types::{BinaryUpdate, EncodingType, ParsedPriceFeedTwap, PriceIdInput, TwapsResponse}, |
| 6 | + ApiState, |
| 7 | + }, |
| 8 | + state::aggregate::{Aggregates, RequestTime}, |
| 9 | + }, |
| 10 | + anyhow::Result, |
| 11 | + axum::{ |
| 12 | + extract::{Path, State}, |
| 13 | + Json, |
| 14 | + }, |
| 15 | + base64::{engine::general_purpose::STANDARD as base64_standard_engine, Engine as _}, |
| 16 | + pyth_sdk::{DurationInSeconds, PriceIdentifier, UnixTimestamp}, |
| 17 | + serde::Deserialize, |
| 18 | + serde_qs::axum::QsQuery, |
| 19 | + utoipa::IntoParams, |
| 20 | +}; |
| 21 | + |
| 22 | +#[derive(Debug, Deserialize, IntoParams)] |
| 23 | +#[into_params(parameter_in=Path)] |
| 24 | +pub struct LatestTwapsPathParams { |
| 25 | + /// The time window in seconds over which to calculate the TWAP, ending at the current time. |
| 26 | + /// For example, a value of 300 would return the most recent 5 minute TWAP. |
| 27 | + /// Must be greater than 0 and less than or equal to 600 seconds (10 minutes). |
| 28 | + #[param(example = "300")] |
| 29 | + #[serde(deserialize_with = "validate_twap_window")] |
| 30 | + window_seconds: u64, |
| 31 | +} |
| 32 | + |
| 33 | +#[derive(Debug, Deserialize, IntoParams)] |
| 34 | +#[into_params(parameter_in=Query)] |
| 35 | +pub struct LatestTwapsQueryParams { |
| 36 | + /// Get the most recent TWAP (time weighted average price) for this set of price feed ids. |
| 37 | + /// The `binary` data contains the signed start & end cumulative price updates needed to calculate |
| 38 | + /// the TWAPs on-chain. The `parsed` data contains the calculated TWAPs. |
| 39 | + /// |
| 40 | + /// This parameter can be provided multiple times to retrieve multiple price updates, |
| 41 | + /// for example see the following query string: |
| 42 | + /// |
| 43 | + /// ``` |
| 44 | + /// ?ids[]=a12...&ids[]=b4c... |
| 45 | + /// ``` |
| 46 | + #[param(rename = "ids[]")] |
| 47 | + #[param(example = "e62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43")] |
| 48 | + ids: Vec<PriceIdInput>, |
| 49 | + |
| 50 | + /// Optional encoding type. If true, return the cumulative price updates in the encoding specified by the encoding parameter. Default is `hex`. |
| 51 | + #[serde(default)] |
| 52 | + encoding: EncodingType, |
| 53 | + |
| 54 | + /// If true, include the calculated TWAP in the `parsed` field of each returned feed. Default is `true`. |
| 55 | + #[serde(default = "default_true")] |
| 56 | + parsed: bool, |
| 57 | + |
| 58 | + /// If true, invalid price IDs in the `ids` parameter are ignored. Only applicable to the v2 APIs. Default is `false`. |
| 59 | + #[serde(default)] |
| 60 | + ignore_invalid_price_ids: bool, |
| 61 | +} |
| 62 | + |
| 63 | +fn validate_twap_window<'de, D>(deserializer: D) -> Result<DurationInSeconds, D::Error> |
| 64 | +where |
| 65 | + D: serde::Deserializer<'de>, |
| 66 | +{ |
| 67 | + use serde::de::Error; |
| 68 | + let seconds = DurationInSeconds::deserialize(deserializer)?; |
| 69 | + if seconds == 0 || seconds > 600 { |
| 70 | + return Err(D::Error::custom( |
| 71 | + "twap_window_seconds must be in range (0, 600]", |
| 72 | + )); |
| 73 | + } |
| 74 | + Ok(seconds) |
| 75 | +} |
| 76 | +fn default_true() -> bool { |
| 77 | + true |
| 78 | +} |
| 79 | + |
| 80 | +/// Get the latest TWAP by price feed id with a custom time window. |
| 81 | +/// |
| 82 | +/// Given a collection of price feed ids, retrieve the latest Pyth TWAP price for each price feed. |
| 83 | +#[utoipa::path( |
| 84 | + get, |
| 85 | + path = "/v2/updates/twap/{window_seconds}/latest", |
| 86 | + responses( |
| 87 | + (status = 200, description = "TWAPs retrieved successfully", body = TwapsResponse), |
| 88 | + (status = 404, description = "Price ids not found", body = String) |
| 89 | + ), |
| 90 | + params( |
| 91 | + LatestTwapsPathParams, |
| 92 | + LatestTwapsQueryParams |
| 93 | + ) |
| 94 | +)] |
| 95 | +pub async fn latest_twaps<S>( |
| 96 | + State(state): State<ApiState<S>>, |
| 97 | + Path(path_params): Path<LatestTwapsPathParams>, |
| 98 | + QsQuery(params): QsQuery<LatestTwapsQueryParams>, |
| 99 | +) -> Result<Json<TwapsResponse>, RestError> |
| 100 | +where |
| 101 | + S: Aggregates, |
| 102 | +{ |
| 103 | + let price_id_inputs: Vec<PriceIdentifier> = |
| 104 | + params.ids.into_iter().map(|id| id.into()).collect(); |
| 105 | + let price_ids: Vec<PriceIdentifier> = |
| 106 | + validate_price_ids(&state, &price_id_inputs, params.ignore_invalid_price_ids).await?; |
| 107 | + |
| 108 | + // Collect start and end bounds for the TWAP window |
| 109 | + let window_seconds = path_params.window_seconds as i64; |
| 110 | + let current_time = std::time::SystemTime::now() |
| 111 | + .duration_since(std::time::UNIX_EPOCH) |
| 112 | + .unwrap() |
| 113 | + .as_secs() as UnixTimestamp; |
| 114 | + let start_time = current_time - window_seconds; |
| 115 | + |
| 116 | + // Calculate the average |
| 117 | + let twaps_with_update_data = Aggregates::get_twaps_with_update_data( |
| 118 | + &*state.state, |
| 119 | + &price_ids, |
| 120 | + RequestTime::FirstAfter(start_time), |
| 121 | + RequestTime::Latest, |
| 122 | + ) |
| 123 | + .await |
| 124 | + .map_err(|e| { |
| 125 | + tracing::warn!( |
| 126 | + "Error getting TWAPs for price IDs {:?} with update data: {:?}", |
| 127 | + price_ids, |
| 128 | + e |
| 129 | + ); |
| 130 | + RestError::UpdateDataNotFound |
| 131 | + })?; |
| 132 | + |
| 133 | + let twap_update_data = twaps_with_update_data.update_data; |
| 134 | + let binary: Vec<BinaryUpdate> = twap_update_data |
| 135 | + .into_iter() |
| 136 | + .map(|data_vec| { |
| 137 | + let encoded_data = data_vec |
| 138 | + .into_iter() |
| 139 | + .map(|data| match params.encoding { |
| 140 | + EncodingType::Base64 => base64_standard_engine.encode(data), |
| 141 | + EncodingType::Hex => hex::encode(data), |
| 142 | + }) |
| 143 | + .collect(); |
| 144 | + BinaryUpdate { |
| 145 | + encoding: params.encoding, |
| 146 | + data: encoded_data, |
| 147 | + } |
| 148 | + }) |
| 149 | + .collect(); |
| 150 | + |
| 151 | + let parsed: Option<Vec<ParsedPriceFeedTwap>> = if params.parsed { |
| 152 | + Some( |
| 153 | + twaps_with_update_data |
| 154 | + .twaps |
| 155 | + .into_iter() |
| 156 | + .map(Into::into) |
| 157 | + .collect(), |
| 158 | + ) |
| 159 | + } else { |
| 160 | + None |
| 161 | + }; |
| 162 | + |
| 163 | + let twap_resp = TwapsResponse { binary, parsed }; |
| 164 | + Ok(Json(twap_resp)) |
| 165 | +} |
0 commit comments