Skip to content

Commit

Permalink
opt: rm oracle_price_active key
Browse files Browse the repository at this point in the history
  • Loading branch information
canonbrother committed Oct 23, 2024
1 parent fcf77f6 commit f099e22
Show file tree
Hide file tree
Showing 6 changed files with 89 additions and 76 deletions.
63 changes: 34 additions & 29 deletions lib/ain-ocean/src/api/loan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ use super::{
use crate::{
error::{ApiError, Error, NotFoundKind, NotFoundSnafu},
model::{OraclePriceActive, VaultAuctionBatchHistory},
storage::{RepositoryOps, SecondaryIndex, SortOrder},
storage::{RepositoryOps, SortOrder},
Result,
};

Expand Down Expand Up @@ -131,13 +131,17 @@ fn get_active_price(
fixed_interval_price_id: String,
) -> Result<Option<OraclePriceActive>> {
let (token, currency) = parse_fixed_interval_price(&fixed_interval_price_id)?;
let repo = &ctx.services.oracle_price_active;
let key = repo.by_key.get(&(token, currency))?;
let price = if let Some(key) = key {
repo.by_id.get(&key)?
} else {
None
};
let price = ctx
.services
.oracle_price_active
.by_id
.list(Some((token, currency, u32::MAX)), SortOrder::Descending)?
.next()
.map(|item| {
let (_, v) = item?;
Ok::<OraclePriceActive, Error>(v)
})
.transpose()?;

Ok(price)
}
Expand Down Expand Up @@ -254,13 +258,17 @@ async fn list_loan_token(
let fixed_interval_price_id = flatten_token.fixed_interval_price_id.clone();
let (token, currency) = parse_fixed_interval_price(&fixed_interval_price_id)?;

let repo = &ctx.services.oracle_price_active;
let key = repo.by_key.get(&(token, currency))?;
let active_price = if let Some(key) = key {
repo.by_id.get(&key)?
} else {
None
};
let active_price = ctx
.services
.oracle_price_active
.by_id
.list(Some((token, currency, u32::MAX)), SortOrder::Descending)?
.next()
.map(|item| {
let (_, v) = item?;
Ok::<OraclePriceActive, Error>(v)
})
.transpose()?;

let token = LoanToken {
token_id: flatten_token.data.creation_tx.clone(),
Expand Down Expand Up @@ -658,23 +666,20 @@ async fn map_token_amounts(
log::error!("Token {token_symbol} not found");
continue;
};
let repo = &ctx.services.oracle_price_active;

let keys = repo
.by_key
.list(None, SortOrder::Descending)?
.collect::<Vec<_>>();
log::trace!("list_auctions keys: {:?}, token_id: {:?}", keys, id);
let active_price = repo
.by_key
.list(None, SortOrder::Descending)?
.take(1)
let active_price = ctx.services.oracle_price_active
.by_id
.list(Some((token_info.symbol.clone(), "USD".to_string(), u32::MAX)), SortOrder::Descending)?
.take_while(|item| match item {
Ok((k, _)) => k.0 == id,
Ok((k, _)) => k.0 == token_info.symbol && k.1 == "USD",
_ => true,
})
.map(|el| repo.by_key.retrieve_primary_value(el))
.collect::<Result<Vec<_>>>()?;
.next()
.map(|item| {
let (_, v) = item?;
Ok::<OraclePriceActive, Error>(v)
})
.transpose()?;

vault_token_amounts.push(VaultTokenAmountResponse {
id,
Expand All @@ -683,7 +688,7 @@ async fn map_token_amounts(
symbol: token_info.symbol,
symbol_key: token_info.symbol_key,
name: token_info.name,
active_price: active_price.first().cloned(),
active_price,
});
}

Expand Down
54 changes: 40 additions & 14 deletions lib/ain-ocean/src/api/prices.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,9 @@ use super::{
AppContext,
};
use crate::{
error::{ApiError, Error, OtherSnafu},
error::{ApiError, OtherSnafu},
model::{
BlockContext, OracleIntervalSeconds, OraclePriceActive,
OraclePriceAggregatedIntervalAggregated, PriceTicker,
BlockContext, OracleIntervalSeconds, OraclePriceActive, OraclePriceActiveNext, OraclePriceAggregatedIntervalAggregated, PriceTicker
},
storage::{RepositoryOps, SortOrder},
Result,
Expand Down Expand Up @@ -233,29 +232,56 @@ async fn get_feed(
))
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct OraclePriceActiveResponse {
pub id: String, // token-currency-height
pub key: String, // token-currency
pub sort: String, // height
pub active: Option<OraclePriceActiveNext>,
pub next: Option<OraclePriceActiveNext>,
pub is_live: bool,
pub block: BlockContext,
}

impl OraclePriceActiveResponse {
fn from_with_id(token: &String, currency: &String, v: OraclePriceActive) -> Self {
Self {
id: format!("{}-{}-{}", token, currency, v.block.height),
key: format!("{}-{}", token, currency),
sort: hex::encode(v.block.height.to_be_bytes()).to_string(),
active: v.active,
next: v.next,
is_live: v.is_live,
block: v.block,
}
}
}

#[ocean_endpoint]
async fn get_feed_active(
Path(key): Path<String>,
Query(query): Query<PaginationQuery>,
Extension(ctx): Extension<Arc<AppContext>>,
) -> Result<ApiPagedResponse<OraclePriceActive>> {
) -> Result<ApiPagedResponse<OraclePriceActiveResponse>> {
let (token, currency) = parse_token_currency(&key)?;

let key = (token, currency);
let repo = &ctx.services.oracle_price_active;
let id = (token.clone(), currency.clone(), u32::MAX);
let price_active = ctx
.services
.oracle_price_active
.by_key
.list(Some(key), SortOrder::Descending)?
.by_id
.list(Some(id), SortOrder::Descending)?
.take_while(|item| match item {
Ok(((t, c, _), _)) => t == &token && c == &currency,
_ => true,
})
.take(query.size)
.flat_map(|item| {
let (_, id) = item?;
let item = repo.by_id.get(&id)?;
Ok::<Option<OraclePriceActive>, Error>(item)
.map(|item| {
let ((token, currency, _), v) = item?;
Ok(OraclePriceActiveResponse::from_with_id(&token, &currency, v))
})
.flatten()
.collect::<Vec<_>>();
.collect::<Result<Vec<_>>>()?;

Ok(ApiPagedResponse::of(price_active, query.size, |price| {
price.sort.to_string()
Expand Down
29 changes: 13 additions & 16 deletions lib/ain-ocean/src/indexer/loan_token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@ pub fn index_active_price(services: &Arc<Services>, block: &BlockContext) -> Res

fn map_active_price(
block: &BlockContext,
ticker_id: (String, String),
aggregated_price: OraclePriceAggregated,
prev_price: Option<OraclePriceActive>,
) -> OraclePriceActive {
Expand All @@ -123,9 +122,6 @@ fn map_active_price(
};

OraclePriceActive {
id: (ticker_id.0.clone(), ticker_id.1.clone(), block.height),
key: ticker_id,
sort: hex::encode(block.height.to_be_bytes()),
active: active_price.clone(),
next: next_price.clone(),
is_live: is_live(active_price, next_price),
Expand Down Expand Up @@ -165,10 +161,12 @@ pub fn perform_active_price_tick(
ticker_id: (Token, Currency),
block: &BlockContext,
) -> Result<()> {
let repo = &services.oracle_price_aggregated;
let prev = repo
let id = (ticker_id.0.clone(), ticker_id.1.clone(), u32::MAX);

let prev = services
.oracle_price_aggregated
.by_id
.list(Some ((ticker_id.0.clone(), ticker_id.1.clone(), u32::MAX)), SortOrder::Descending)?
.list(Some (id.clone()), SortOrder::Descending)?
.next()
.transpose()?;

Expand All @@ -177,23 +175,22 @@ pub fn perform_active_price_tick(
};

let repo = &services.oracle_price_active;
let prev_key = repo
.by_key
.list(Some(ticker_id.clone()), SortOrder::Descending)?
let prev = repo
.by_id
.list(Some(id.clone()), SortOrder::Descending)?
.next()
.transpose()?;

let prev_price = if let Some((_, prev_id)) = prev_key {
repo.by_id.get(&prev_id)?
let prev_price = if let Some((_, prev)) = prev {
Some(prev)
} else {
None
};

let active_price = map_active_price(block, ticker_id, aggregated_price, prev_price);

repo.by_id.put(&active_price.id, &active_price)?;
let active_price = map_active_price(block, aggregated_price, prev_price);

repo.by_key.put(&active_price.key, &active_price.id)?;
let new_id = (id.0, id.1, block.height);
repo.by_id.put(&new_id, &active_price)?;

Ok(())
}
2 changes: 0 additions & 2 deletions lib/ain-ocean/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ pub struct OraclePriceFeedService {
by_id: OraclePriceFeed,
}
pub struct OraclePriceActiveService {
by_key: OraclePriceActiveKey,
by_id: OraclePriceActive,
}
pub struct OraclePriceAggregatedIntervalService {
Expand Down Expand Up @@ -181,7 +180,6 @@ impl Services {
by_id: OraclePriceFeed::new(Arc::clone(&store)),
},
oracle_price_active: OraclePriceActiveService {
by_key: OraclePriceActiveKey::new(Arc::clone(&store)),
by_id: OraclePriceActive::new(Arc::clone(&store)),
},
oracle_price_aggregated_interval: OraclePriceAggregatedIntervalService {
Expand Down
5 changes: 1 addition & 4 deletions lib/ain-ocean/src/model/oracle_price_active.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,10 @@ use serde::{Deserialize, Serialize};
use super::BlockContext;

pub type OraclePriceActiveId = (String, String, u32); //token-currency-height
pub type OraclePriceActiveKey = (String, String); //token-currency

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct OraclePriceActive {
pub id: OraclePriceActiveId,
pub key: OraclePriceActiveKey,
pub sort: String, //height
pub active: Option<OraclePriceActiveNext>,
pub next: Option<OraclePriceActiveNext>,
pub is_live: bool,
Expand Down
12 changes: 1 addition & 11 deletions lib/ain-ocean/src/storage/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,15 +164,6 @@ define_table! {
}
}

define_table! {
#[derive(Debug)]
pub struct OraclePriceActiveKey {
key_type = model::OraclePriceActiveKey,
value_type = model::OraclePriceActiveId,
},
SecondaryIndex = OraclePriceActive
}

define_table! {
#[derive(Debug)]
pub struct OraclePriceAggregated {
Expand Down Expand Up @@ -426,7 +417,7 @@ define_table! {
SecondaryIndex = VaultAuctionHistory
}

pub const COLUMN_NAMES: [&str; 30] = [
pub const COLUMN_NAMES: [&str; 29] = [
Block::NAME,
BlockByHeight::NAME,
MasternodeStats::NAME,
Expand All @@ -435,7 +426,6 @@ pub const COLUMN_NAMES: [&str; 30] = [
Oracle::NAME,
OracleHistory::NAME,
OraclePriceActive::NAME,
OraclePriceActiveKey::NAME,
OraclePriceAggregated::NAME,
OraclePriceAggregatedInterval::NAME,
OraclePriceFeed::NAME,
Expand Down

0 comments on commit f099e22

Please sign in to comment.