Skip to content
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

Ocean list pool swap verbose api #2926

Merged
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions lib/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ vsdbsled = { git = "https://github.com/defich/vsdbsled.git" }
ethereum = { git = "https://github.com/defich/ethereum.git" }
evm = { git = "https://github.com/defich/evm.git" }
evm-runtime = { git = "https://github.com/defich/evm.git" }
bitcoin = { git = "https://github.com/defich/rust-bitcoin.git" }
bitcoin-io = { git = "https://github.com/defich/rust-bitcoin.git" }
bitcoin = { git = "https://github.com/defich/rust-bitcoin.git", branch = "canonbrother/defichain-network" }
bitcoin-io = { git = "https://github.com/defich/rust-bitcoin.git", branch = "canonbrother/defichain-network" }
canonbrother marked this conversation as resolved.
Show resolved Hide resolved

[workspace.dependencies]

Expand Down
2 changes: 0 additions & 2 deletions lib/ain-ocean/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,6 @@ pub async fn ocean_router(
.nest("/masternodes", masternode::router(Arc::clone(&context)))
.nest("/oracles", oracle::router(Arc::clone(&context)))
.nest("/poolpairs", pool_pair::router(Arc::clone(&context)))
// .nest("/prices", prices::router(Arc::clone(&context)))
// .nest("/poolpairs", poolpairs::router(Arc::clone(&context)))
.nest("/prices", prices::router(Arc::clone(&context)))
// .nest("/rawtx", rawtx::router(Arc::clone(&context)))
.nest("/stats", stats::router(Arc::clone(&context)))
Expand Down
61 changes: 27 additions & 34 deletions lib/ain-ocean/src/api/pool_pair/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@ use petgraph::graphmap::UnGraphMap;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use serde_json::json;
use serde_with::skip_serializing_none;
use service::{
get_aggregated_in_usd, get_apr, get_total_liquidity_usd, get_usd_volume, PoolPairVolumeResponse,
check_swap_type, find_swap_from_to, get_aggregated_in_usd, get_apr, get_total_liquidity_usd,
get_usd_volume, PoolPairVolumeResponse, PoolSwapFromTo, PoolSwapFromToData, SwapType,
};

use super::{
Expand Down Expand Up @@ -64,15 +66,7 @@ struct DexPrices {
denomination: String,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct PoolSwapFromToResponse {
address: String,
amount: String,
// symbol: String,
// display_symbol: String,
}

#[skip_serializing_none]
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct PoolSwapVerboseResponse {
Expand All @@ -84,35 +78,25 @@ pub struct PoolSwapVerboseResponse {
from_amount: String,
from_token_id: u64,
block: BlockContext,
from: PoolSwapFromToResponse,
to: PoolSwapFromToResponse,
// type: todo()!
from: Option<PoolSwapFromToData>,
to: Option<PoolSwapFromToData>,
r#type: Option<SwapType>,
}

impl From<PoolSwap> for PoolSwapVerboseResponse {
fn from(v: PoolSwap) -> Self {
impl PoolSwapVerboseResponse {
fn map(v: PoolSwap, from_to: Option<PoolSwapFromTo>, swap_type: Option<SwapType>) -> Self {
Self {
id: v.id,
sort: v.sort,
txid: v.txid.to_string(),
txno: v.txno,
pool_pair_id: v.pool_id.to_string(),
from_amount: v.from_amount.to_string(),
from_amount: Decimal::new(v.from_amount, 8).to_string(),
from_token_id: v.from_token_id,
from: PoolSwapFromToResponse {
address: v.from.to_hex_string(),
amount: v.from_amount.to_string(),
// symbol: todo!(),
// display_symbol: todo!(),
},
to: PoolSwapFromToResponse {
address: v.to.to_hex_string(),
amount: v.to_amount.to_string(),
// symbol: todo!(),
// display_symbol: todo!(),
},
from: from_to.clone().and_then(|item| item.from),
to: from_to.and_then(|item| item.to),
block: v.block,
// type: todo!(),
r#type: swap_type,
}
}
}
Expand Down Expand Up @@ -456,9 +440,9 @@ async fn list_pool_swaps_verbose(
.transpose()?
.unwrap_or(PoolSwapRepository::initial_key(id));

let size = if query.size > 200 { 200 } else { query.size };
let size = if query.size > 20 { 20 } else { query.size };

let swaps = ctx
let fut = ctx
.services
.pool
.by_id
Expand All @@ -468,11 +452,20 @@ async fn list_pool_swaps_verbose(
Ok((k, _)) => k.0 == id,
_ => true,
})
.map(|item| {
.map(|item| async {
let (_, swap) = item?;
Ok(PoolSwapVerboseResponse::from(swap))
let from_to =
find_swap_from_to(&ctx, swap.block.height, swap.txid, swap.txno.try_into()?)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is expensive and should only be done if we haven't indexed the TxResult::PoolSwap.
Should make the TxResult::PoolSwap optional in the PoolSwap Index implementation

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the poolswap index impl is interesting.. checking...

Copy link
Contributor Author

@canonbrother canonbrother Jun 6, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if its not mistaken.. only need to execute the TxResult::PoolSwap with -oceanarchive flag to reduce op cost
a4af36b

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

// TODO fallback through getaccounthistory when indexing against non-oceanarchive node
// let address = Address::from_script(&self.to_script, bitcoin::Network::Bitcoin)
// .map_err(|e| format_err!("Error getting address from script: {e}"));

another blocker for deployment.. fixing it at another PR

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can remove this fallback at the indexing layer since this PR includes a fallback at the API level.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can already do a deployment with the -oceanarchive flag set and a full sync

.await?;

let swap_type = check_swap_type(&ctx, swap.clone()).await?;

let res = PoolSwapVerboseResponse::map(swap, from_to, swap_type);
Ok::<PoolSwapVerboseResponse, Error>(res)
})
.collect::<Result<Vec<_>>>()?;
.collect::<Vec<_>>();

let swaps = try_join_all(fut).await?;

Ok(ApiPagedResponse::of(swaps, query.size, |swap| {
swap.sort.to_string()
Expand Down
7 changes: 4 additions & 3 deletions lib/ain-ocean/src/api/pool_pair/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::{collections::HashSet, str::FromStr, sync::Arc, time::Duration};

use anyhow::format_err;
use defichain_rpc::json::poolpair::PoolPairInfo;
use log::debug;
use rust_decimal::{prelude::FromPrimitive, Decimal};
use rust_decimal_macros::dec;
use serde::Serialize;
Expand All @@ -19,7 +20,7 @@ use crate::{

enum TokenDirection {
In,
Out
Out,
}

#[derive(Debug, Serialize)]
Expand Down Expand Up @@ -323,7 +324,7 @@ fn get_dex_fees_pct(
ab: match token_b_direction {
TokenDirection::In => format!("{:.8}", dex_fee_in_pct_token_b.unwrap_or_default()),
TokenDirection::Out => format!("{:.8}", dex_fee_out_pct_token_b.unwrap_or_default()),
}
},
})
}

Expand Down Expand Up @@ -518,7 +519,7 @@ pub async fn sync_token_graph(ctx: &Arc<AppContext>) -> Result<()> {
if !graph.lock().contains_edge(id_token_a, id_token_b) {
graph.lock().add_edge(id_token_a, id_token_b, k);
}
log::debug!("sync_token_graph edges: {:?}", graph.lock().edge_count());
debug!("sync_token_graph edges: {:?}", graph.lock().edge_count());
}

// wait 120s
Expand Down
Loading
Loading