Skip to content

Commit

Permalink
Ocean: cache pool utils (#3069)
Browse files Browse the repository at this point in the history
* cache pool utils

* get_network_info_cached

* guard
  • Loading branch information
canonbrother authored Sep 26, 2024
1 parent 3748eb9 commit 9a6ce3a
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 13 deletions.
14 changes: 13 additions & 1 deletion lib/ain-ocean/src/api/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ use defichain_rpc::{
loan::LoanSchemeResult,
poolpair::{PoolPairInfo, PoolPairPagination, PoolPairsResult},
token::{TokenInfo, TokenPagination, TokenResult},
GetNetworkInfoResult,
},
jsonrpc_async::error::{Error as JsonRpcError, RpcError},
Error, LoanRPC, MasternodeRPC, PoolPairRPC, TokenRPC,
Error, LoanRPC, MasternodeRPC, PoolPairRPC, RpcApi, TokenRPC,
};

use super::AppContext;
Expand Down Expand Up @@ -159,3 +160,14 @@ pub async fn get_loan_scheme_cached(ctx: &Arc<AppContext>, id: String) -> Result
let loan_scheme = ctx.client.get_loan_scheme(id).await?;
Ok(loan_scheme)
}

#[cached(
result = true,
time = 600,
key = "String",
convert = r#"{ format!("getnetworkinfo") }"#
)]
pub async fn get_network_info_cached(ctx: &Arc<AppContext>) -> Result<GetNetworkInfoResult> {
let info = ctx.client.get_network_info().await?;
Ok(info)
}
43 changes: 37 additions & 6 deletions lib/ain-ocean/src/api/pool_pair/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::{collections::HashMap, str::FromStr, sync::Arc};

use ain_dftx::{deserialize, pool::CompositeSwap, DfTx, Stack};
use bitcoin::Txid;
use cached::proc_macro::cached;
use defichain_rpc::{json::poolpair::PoolPairInfo, BlockchainRPC};
use rust_decimal::{prelude::FromPrimitive, Decimal};
use rust_decimal_macros::dec;
Expand Down Expand Up @@ -54,6 +55,12 @@ pub struct PoolSwapFromTo {
pub to: Option<PoolSwapFromToData>,
}

#[cached(
result = true,
time = 600,
key = "String",
convert = r#"{ format!("getusdperdfi") }"#
)]
pub async fn get_usd_per_dfi(ctx: &Arc<AppContext>) -> Result<Decimal> {
let usdt = get_pool_pair_cached(ctx, "USDT-DFI".to_string()).await?;

Expand Down Expand Up @@ -226,6 +233,12 @@ async fn get_yearly_custom_reward_usd(ctx: &Arc<AppContext>, p: &PoolPairInfo) -
})
}

#[cached(
result = true,
time = 600,
key = "String",
convert = r#"{ format!("getdailydfireward") }"#
)]
async fn get_daily_dfi_reward(ctx: &Arc<AppContext>) -> Result<Decimal> {
let gov = get_gov_cached(ctx, "LP_DAILY_DFI_REWARD".to_string()).await?;

Expand All @@ -247,10 +260,6 @@ async fn get_loan_token_splits(ctx: &Arc<AppContext>) -> Result<Option<serde_jso
}

async fn get_yearly_reward_pct_usd(ctx: &Arc<AppContext>, p: &PoolPairInfo) -> Result<Decimal> {
// if p.reward_pct.is_none() {
// return dec!(0)
// };

let dfi_price_usd = get_usd_per_dfi(ctx).await?;
let daily_dfi_reward = get_daily_dfi_reward(ctx).await?;

Expand Down Expand Up @@ -297,7 +306,12 @@ async fn get_block_subsidy(eunos_height: u32, height: u32) -> Result<Decimal> {
Ok(block_subsidy)
}

// TODO(): cached
#[cached(
result = true,
time = 600,
key = "String",
convert = r#"{ format!("getloanemission") }"#
)]
async fn get_loan_emission(ctx: &Arc<AppContext>) -> Result<Decimal> {
let info = ctx.client.get_blockchain_info().await?;
let eunos_height = info
Expand All @@ -313,12 +327,17 @@ async fn get_loan_emission(ctx: &Arc<AppContext>) -> Result<Decimal> {

async fn get_yearly_reward_loan_usd(ctx: &Arc<AppContext>, id: &String) -> Result<Decimal> {
let splits = get_loan_token_splits(ctx).await?;
let value = splits.unwrap_or_default();
let Some(value) = splits else {
return Ok(dec!(0));
};
let split = value
.as_object()
.and_then(|obj| obj.get(id))
.and_then(serde_json::Value::as_f64)
.unwrap_or_default();
if split == 0.0 {
return Ok(dec!(0));
}
let split = Decimal::from_f64(split).context(DecimalConversionSnafu)?;

let dfi_price_usd = get_usd_per_dfi(ctx).await?;
Expand Down Expand Up @@ -397,6 +416,12 @@ async fn gather_amount(
Ok(volume)
}

#[cached(
result = true,
time = 900, // 15 mins
key = "String",
convert = r#"{ format!("getusdvolume{id}") }"#
)]
pub async fn get_usd_volume(ctx: &Arc<AppContext>, id: &str) -> Result<PoolPairVolumeResponse> {
let pool_id = id.parse::<u32>()?;
Ok(PoolPairVolumeResponse {
Expand Down Expand Up @@ -475,6 +500,12 @@ async fn get_pool_pair(ctx: &Arc<AppContext>, a: &str, b: &str) -> Result<Option
}
}

#[cached(
result = true,
time = 300, // 5 mins
key = "String",
convert = r#"{ format!("gettokenusdvalue{token_id}") }"#
)]
async fn get_token_usd_value(ctx: &Arc<AppContext>, token_id: &u64) -> Result<Decimal> {
let info = ain_cpp_imports::get_dst_token(token_id.to_string());
if info.is_null() {
Expand Down
12 changes: 6 additions & 6 deletions lib/ain-ocean/src/api/stats/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,22 @@ use ain_macros::ocean_endpoint;
use axum::{routing::get, Extension, Router};
use defichain_rpc::{
defichain_rpc_json::{account::BurnInfo, GetNetworkInfoResult},
AccountRPC, RpcApi,
AccountRPC,
};
use rust_decimal::{prelude::FromPrimitive, Decimal};
use serde::{Deserialize, Serialize};
use snafu::OptionExt;

use self::{
cache::{
get_burned, get_count, get_emission, get_loan, get_masternodes, get_price, get_tvl, Burned,
Count, Emission, Loan, Masternodes, Price, Tvl,
get_burned, get_burned_total, get_count, get_emission, get_loan, get_masternodes,
get_price, get_tvl, Burned, Count, Emission, Loan, Masternodes, Price, Tvl,
},
distribution::get_block_reward_distribution,
subsidy::BLOCK_SUBSIDY,
};
use super::{response::Response, AppContext};
use super::{cache::get_network_info_cached, response::Response, AppContext};
use crate::{
api::stats::{cache::get_burned_total, subsidy::BLOCK_SUBSIDY},
error::{ApiError, DecimalConversionSnafu},
Result,
};
Expand Down Expand Up @@ -69,7 +69,7 @@ async fn get_stats(Extension(ctx): Extension<Arc<AppContext>>) -> Result<Respons
subversion,
protocol_version,
..
} = ctx.client.get_network_info().await?;
} = get_network_info_cached(&ctx).await?;

let stats = StatsData {
burned: get_burned(&ctx.client).await?,
Expand Down

0 comments on commit 9a6ce3a

Please sign in to comment.