Skip to content

Commit

Permalink
Improve last token native price sql query (#3269)
Browse files Browse the repository at this point in the history
  • Loading branch information
squadgazzz authored Feb 6, 2025
1 parent 5874a92 commit afe10d0
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 13 deletions.
35 changes: 22 additions & 13 deletions crates/orderbook/src/database/orders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -493,39 +493,48 @@ impl Postgres {
}

pub async fn token_metadata(&self, token: &H160) -> Result<TokenMetadata> {
let timer = super::Metrics::get()
.database_queries
.with_label_values(&["token_first_trade_block"])
.start_timer();

let (first_trade_block, native_price) = tokio::try_join!(
async {
let (first_trade_block, native_price): (Option<u32>, Option<U256>) = tokio::try_join!(
self.execute_instrumented("token_first_trade_block", async {
let mut ex = self.pool.acquire().await?;
database::trades::token_first_trade_block(&mut ex, ByteArray(token.0))
.await
.map_err(anyhow::Error::from)?
.map(u32::try_from)
.transpose()
.map_err(anyhow::Error::from)
},
async {
}),
self.execute_instrumented("fetch_latest_token_price", async {
let mut ex = self.pool.acquire().await?;
Ok::<Option<U256>, anyhow::Error>(
Ok(
database::auction_prices::fetch_latest_token_price(&mut ex, ByteArray(token.0))
.await
.map_err(anyhow::Error::from)?
.and_then(|price| big_decimal_to_u256(&price)),
)
}
})
)?;

timer.stop_and_record();

Ok(TokenMetadata {
first_trade_block,
native_price,
})
}

async fn execute_instrumented<F, T>(&self, label: &str, f: F) -> Result<T>
where
F: std::future::Future<Output = Result<T>>,
{
let timer = super::Metrics::get()
.database_queries
.with_label_values(&[label])
.start_timer();

let result = f.await?;

timer.observe_duration();

Ok(result)
}
}

#[async_trait]
Expand Down
2 changes: 2 additions & 0 deletions database/sql/V079__auction_prices_token_index.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- Create index to improve `fetch_latest_token_price` query performance.
CREATE INDEX auction_prices_token_auction_id_idx ON auction_prices (token, auction_id DESC);

0 comments on commit afe10d0

Please sign in to comment.