-
Notifications
You must be signed in to change notification settings - Fork 300
feat(hermes): create latest TWAP endpoint #2126
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,162 @@ | ||
use { | ||
crate::{ | ||
api::{ | ||
rest::{validate_price_ids, RestError}, | ||
types::{BinaryUpdate, EncodingType, PriceIdInput, RpcPriceFeedTwap, TwapsResponse}, | ||
ApiState, | ||
}, | ||
state::aggregate::{Aggregates, RequestTime}, | ||
}, | ||
anyhow::Result, | ||
axum::{ | ||
extract::{Path, State}, | ||
Json, | ||
}, | ||
base64::{engine::general_purpose::STANDARD as base64_standard_engine, Engine as _}, | ||
pyth_sdk::{DurationInSeconds, PriceIdentifier, UnixTimestamp}, | ||
serde::Deserialize, | ||
serde_qs::axum::QsQuery, | ||
utoipa::IntoParams, | ||
}; | ||
|
||
#[derive(Debug, Deserialize, IntoParams)] | ||
#[into_params(parameter_in=Path)] | ||
pub struct LatestTwapsPathParams { | ||
/// The time window in seconds over which to calculate the TWAP, ending at the current time. | ||
/// For example, a value of 300 would return the most recent 5 minute TWAP. | ||
/// Must be greater than 0 and less than or equal to 600 seconds (10 minutes). | ||
#[param(example = "300")] | ||
#[serde(deserialize_with = "validate_twap_window")] | ||
window_seconds: u64, | ||
} | ||
|
||
#[derive(Debug, Deserialize, IntoParams)] | ||
#[into_params(parameter_in=Query)] | ||
pub struct LatestTwapsQueryParams { | ||
/// Get the most recent TWAP (time weighted average price) for this set of price feed ids. | ||
/// | ||
/// This parameter can be provided multiple times to retrieve multiple price updates, | ||
/// for example see the following query string: | ||
/// | ||
/// ``` | ||
/// ?ids[]=a12...&ids[]=b4c... | ||
/// ``` | ||
#[param(rename = "ids[]")] | ||
#[param(example = "e62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43")] | ||
ids: Vec<PriceIdInput>, | ||
|
||
/// Optional encoding type. If true, return the price update in the encoding specified by the encoding parameter. Default is `hex`. | ||
#[serde(default)] | ||
encoding: EncodingType, | ||
|
||
/// If true, include the parsed price update in the `parsed` field of each returned feed. Default is `true`. | ||
#[serde(default = "default_true")] | ||
parsed: bool, | ||
|
||
/// If true, invalid price IDs in the `ids` parameter are ignored. Only applicable to the v2 APIs. Default is `false`. | ||
#[serde(default)] | ||
ignore_invalid_price_ids: bool, | ||
} | ||
|
||
fn validate_twap_window<'de, D>(deserializer: D) -> Result<DurationInSeconds, D::Error> | ||
where | ||
D: serde::Deserializer<'de>, | ||
{ | ||
use serde::de::Error; | ||
let seconds = DurationInSeconds::deserialize(deserializer)?; | ||
if seconds == 0 || seconds > 600 { | ||
return Err(D::Error::custom( | ||
"twap_window_seconds must be in range (0, 600]", | ||
)); | ||
} | ||
Ok(seconds) | ||
} | ||
fn default_true() -> bool { | ||
true | ||
} | ||
|
||
/// Get the latest TWAP by price feed id. | ||
/// | ||
/// Given a collection of price feed ids, retrieve the latest Pyth price for each price feed. | ||
#[utoipa::path( | ||
get, | ||
path = "/v2/updates/twap/{window_seconds}/latest", | ||
responses( | ||
(status = 200, description = "TWAPs retrieved successfully", body = TwapsResponse), | ||
(status = 404, description = "Price ids not found", body = String) | ||
), | ||
params( | ||
LatestTwapsPathParams, | ||
LatestTwapsQueryParams | ||
) | ||
)] | ||
pub async fn latest_twaps<S>( | ||
State(state): State<ApiState<S>>, | ||
Path(path_params): Path<LatestTwapsPathParams>, | ||
QsQuery(params): QsQuery<LatestTwapsQueryParams>, | ||
) -> Result<Json<TwapsResponse>, RestError> | ||
where | ||
S: Aggregates, | ||
{ | ||
let price_id_inputs: Vec<PriceIdentifier> = | ||
params.ids.into_iter().map(|id| id.into()).collect(); | ||
let price_ids: Vec<PriceIdentifier> = | ||
validate_price_ids(&state, &price_id_inputs, params.ignore_invalid_price_ids).await?; | ||
|
||
// Collect start and end bounds for the TWAP window | ||
let window_seconds = path_params.window_seconds as i64; | ||
let current_time = std::time::SystemTime::now() | ||
.duration_since(std::time::UNIX_EPOCH) | ||
.unwrap() | ||
.as_secs() as UnixTimestamp; | ||
let start_time = current_time - window_seconds; | ||
|
||
// Calculate the average | ||
let twaps_with_update_data = Aggregates::get_twaps_with_update_data( | ||
&*state.state, | ||
&price_ids, | ||
RequestTime::FirstAfter(start_time), | ||
RequestTime::Latest, | ||
) | ||
.await | ||
.map_err(|e| { | ||
tracing::warn!( | ||
"Error getting TWAPs for price IDs {:?} with update data: {:?}", | ||
price_ids, | ||
e | ||
); | ||
RestError::UpdateDataNotFound | ||
})?; | ||
|
||
// Include binary update data for the messages used to calculate the TWAP | ||
let twap_update_data = twaps_with_update_data.update_data; | ||
let encoded_data: Vec<String> = twap_update_data | ||
.into_iter() | ||
.map(|data| match params.encoding { | ||
EncodingType::Base64 => base64_standard_engine.encode(data), | ||
EncodingType::Hex => hex::encode(data), | ||
}) | ||
.collect(); | ||
let binary_price_update = BinaryUpdate { | ||
encoding: params.encoding, | ||
data: encoded_data, | ||
}; | ||
let parsed_twaps: Option<Vec<RpcPriceFeedTwap>> = if params.parsed { | ||
Some( | ||
twaps_with_update_data | ||
.twaps | ||
.into_iter() | ||
.map(Into::into) | ||
.collect(), | ||
) | ||
} else { | ||
None | ||
}; | ||
|
||
let twap_resp = TwapsResponse { | ||
binary: binary_price_update, | ||
parsed: parsed_twaps, | ||
}; | ||
|
||
Ok(Json(twap_resp)) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,6 @@ | ||
pub mod latest_price_updates; | ||
pub mod latest_publisher_stake_caps; | ||
pub mod latest_twaps; | ||
pub mod price_feeds_metadata; | ||
pub mod sse; | ||
pub mod timestamp_price_updates; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we probably need down_slots as well right?