Skip to content

Commit

Permalink
fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
canonbrother committed Jul 16, 2024
1 parent 95eef3b commit deb8459
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 41 deletions.
19 changes: 12 additions & 7 deletions lib/ain-ocean/src/api/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@ use std::{collections::HashMap, sync::Arc};
use cached::proc_macro::cached;
use defichain_rpc::{
json::{
loan::LoanSchemeResult, poolpair::{PoolPairInfo, PoolPairPagination, PoolPairsResult}, token::{TokenInfo, TokenPagination, TokenResult}
}, jsonrpc_async::error::{Error as JsonRpcError, RpcError}, Error, LoanRPC, MasternodeRPC, PoolPairRPC, TokenRPC
loan::LoanSchemeResult,
poolpair::{PoolPairInfo, PoolPairPagination, PoolPairsResult},
token::{TokenInfo, TokenPagination, TokenResult},
},
jsonrpc_async::error::{Error as JsonRpcError, RpcError},
Error, LoanRPC, MasternodeRPC, PoolPairRPC, TokenRPC,
};

use super::AppContext;
Expand Down Expand Up @@ -127,11 +131,12 @@ pub async fn get_gov_cached(
Ok(gov)
}

#[cached(result = true, key = "String", convert = r#"{ format!("getloanscheme{id}") }"#)]
pub async fn get_loan_scheme_cached(
ctx: &Arc<AppContext>,
id: String,
) -> Result<LoanSchemeResult> {
#[cached(
result = true,
key = "String",
convert = r#"{ format!("getloanscheme{id}") }"#
)]
pub async fn get_loan_scheme_cached(ctx: &Arc<AppContext>, id: String) -> Result<LoanSchemeResult> {
let loan_scheme = ctx.client.get_loan_scheme(id).await?;
Ok(loan_scheme)
}
52 changes: 34 additions & 18 deletions lib/ain-ocean/src/api/loan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,16 @@ use defichain_rpc::{
loan::{CollateralTokenDetail, LoanSchemeResult},
token::TokenInfo,
vault::VaultLiquidationBatch,
}, json::vault::{AuctionPagination, AuctionPaginationStart}, LoanRPC, VaultRPC
},
json::vault::{AuctionPagination, AuctionPaginationStart},
LoanRPC, VaultRPC,
};
use futures::future::try_join_all;
use log::debug;
use serde::Serialize;

use super::{
cache::{get_token_cached, get_loan_scheme_cached},
cache::{get_loan_scheme_cached, get_token_cached},
common::{from_script, parse_display_symbol, Paginate},
path::Path,
query::{PaginationQuery, Query},
Expand Down Expand Up @@ -334,22 +336,17 @@ pub struct VaultTokenAmountResponse {
pub active_price: Option<OraclePriceActive>,
}


#[ocean_endpoint]
async fn list_auction(
Query(query): Query<PaginationQuery>,
Extension(ctx): Extension<Arc<AppContext>>,
) -> Result<ApiPagedResponse<VaultLiquidationResponse>> {

let start = query
.next
.as_ref()
.map(|next| {
let start = query.next.as_ref().map(|next| {
let vault_id = &next[0..64];
let height = &next[64..];
AuctionPaginationStart {
vault_id: vault_id.to_string(),
height: height.parse::<u64>().unwrap_or_default(),
vault_id: vault_id.to_string(),
height: height.parse::<u64>().unwrap_or_default(),
}
});

Expand All @@ -363,7 +360,11 @@ async fn list_auction(
},
};

async fn map_liquidation_batches(ctx: &Arc<AppContext>, vault_id: &str, batches: Vec<VaultLiquidationBatch>) -> Result<Vec<VaultLiquidationBatchResponse>> {
async fn map_liquidation_batches(
ctx: &Arc<AppContext>,
vault_id: &str,
batches: Vec<VaultLiquidationBatch>,
) -> Result<Vec<VaultLiquidationBatchResponse>> {
let repo = &ctx.services.auction;
let mut vec = Vec::new();
for batch in batches {
Expand All @@ -377,12 +378,18 @@ async fn list_auction(
} else {
None
};
let id = (Txid::from_str(vault_id)?, batch.index, Txid::from_byte_array([0xffu8; 32]));
let id = (
Txid::from_str(vault_id)?,
batch.index,
Txid::from_byte_array([0xffu8; 32]),
);
let bids = repo
.by_id
.list(Some(id), SortOrder::Descending)?
.take_while(|item| match item {
Ok(((vid, bindex, _), _)) => vid.to_string() == vault_id && bindex == &batch.index,
Ok(((vid, bindex, _), _)) => {
vid.to_string() == vault_id && bindex == &batch.index
}
_ => true,
})
.collect::<Vec<_>>();
Expand All @@ -397,17 +404,23 @@ async fn list_auction(
vec.push(VaultLiquidationBatchResponse {
index: batch.index,
collaterals: map_token_amounts(ctx, batch.collaterals).await?,
loan: map_token_amounts(ctx, vec![batch.loan]).await?.first().cloned(),
loan: map_token_amounts(ctx, vec![batch.loan])
.await?
.first()
.cloned(),
froms,
highest_bid,
})
}
Ok(vec)
}

async fn map_token_amounts(ctx: &Arc<AppContext>, amounts: Vec<String>) -> Result<Vec<VaultTokenAmountResponse>> {
async fn map_token_amounts(
ctx: &Arc<AppContext>,
amounts: Vec<String>,
) -> Result<Vec<VaultTokenAmountResponse>> {
if amounts.is_empty() {
return Ok(Vec::new())
return Ok(Vec::new());
}
let amount_token_symbols = amounts
.into_iter()
Expand All @@ -425,11 +438,14 @@ async fn list_auction(
let token = get_token_cached(ctx, &token_symbol).await?;
if token.is_none() {
log::error!("Token {token_symbol} not found");
continue
continue;
}
let repo = &ctx.services.oracle_price_active;
let (id, token_info) = token.unwrap();
let keys = repo.by_key.list(None, SortOrder::Descending)?.collect::<Vec<_>>();
let keys = repo
.by_key
.list(None, SortOrder::Descending)?
.collect::<Vec<_>>();
log::debug!("list_auctions keys: {:?}, token_id: {:?}", keys, id);
let active_price = repo
.by_key
Expand Down
36 changes: 20 additions & 16 deletions lib/ain-ocean/src/indexer/loan_token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,13 @@ impl Index for SetLoanToken {
})
.collect::<Result<Vec<_>>>()?;

log::debug!("set_loan_token indexing aggregated_price: {:?}", aggregated_prices);
log::debug!(
"set_loan_token indexing aggregated_price: {:?}",
aggregated_prices
);

if aggregated_prices.is_empty() {
return Ok(())
return Ok(());
}
let aggregated_price = aggregated_prices.first().unwrap();

Expand Down Expand Up @@ -98,7 +101,7 @@ impl Index for SetLoanToken {
oracles: OraclePriceActiveNextOracles {
active: aggregated_price.aggregated.oracles.active,
total: aggregated_price.aggregated.oracles.total,
}
},
})
} else {
None
Expand All @@ -124,7 +127,10 @@ impl Index for SetLoanToken {
.by_key
.put(&oracle_price_active.key, &oracle_price_active.id)?;

log::debug!("set_loan_token indexing oracle_price_active: {:?}", oracle_price_active);
log::debug!(
"set_loan_token indexing oracle_price_active: {:?}",
oracle_price_active
);

Ok(())
}
Expand All @@ -146,30 +152,28 @@ impl Index for SetLoanToken {

fn is_aggregate_valid(aggregate: &OraclePriceAggregated, context: &Context) -> bool {
if (aggregate.block.time - context.block.time).abs() >= 3600 {
return false
return false;
}

if aggregate.aggregated.oracles.active < 2 { // minimum live oracles
return false
if aggregate.aggregated.oracles.active < 2 {
// minimum live oracles
return false;
}

if aggregate.aggregated.weightage <= 0 {
return false
return false;
}

true
}

fn is_live(
active: Option<OraclePriceActiveActive>,
next: Option<OraclePriceActiveNext>,
) -> bool {
fn is_live(active: Option<OraclePriceActiveActive>, next: Option<OraclePriceActiveNext>) -> bool {
if active.is_none() {
return false
return false;
}

if next.is_none() {
return false
return false;
}

let active = active.unwrap();
Expand All @@ -186,11 +190,11 @@ fn is_live(
};

if active_price <= Decimal::zero() {
return false
return false;
}

if next_price <= Decimal::zero() {
return false
return false;
}

let diff = (next_price - active_price).abs();
Expand Down

0 comments on commit deb8459

Please sign in to comment.