Skip to content

Commit

Permalink
Index swap and swap result (#2778)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jouzo authored Jan 12, 2024
1 parent 24e2997 commit ce29359
Show file tree
Hide file tree
Showing 26 changed files with 596 additions and 252 deletions.
287 changes: 141 additions & 146 deletions lib/Cargo.lock

Large diffs are not rendered by default.

27 changes: 9 additions & 18 deletions lib/ain-ocean/src/api/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,13 @@ use axum::{
use bitcoin::BlockHash;

use crate::{
api_paged_response::ApiPagedResponse,
api_query::PaginationQuery,
error::OceanResult,
SERVICES,
repository::RepositoryOps,
model::Block,
api_paged_response::ApiPagedResponse, api_query::PaginationQuery, model::Block,
repository::RepositoryOps, Result, SERVICES,
};

async fn list_blocks(
Query(query): Query<PaginationQuery>,
) -> OceanResult<Json<ApiPagedResponse<Block>>> {
) -> Result<Json<ApiPagedResponse<Block>>> {
let blocks = SERVICES
.block
.by_height
Expand All @@ -32,20 +28,15 @@ async fn list_blocks(

Ok(b)
})
.collect::<OceanResult<Vec<_>>>()?;
.collect::<Result<Vec<_>>>()?;

Ok(Json(ApiPagedResponse::of(
blocks,
query.size,
|block| block.clone().id,
)))
Ok(Json(ApiPagedResponse::of(blocks, query.size, |block| {
block.clone().id
})))
}

async fn get_block(Path(id): Path<BlockHash>) -> OceanResult<Json<Option<Block>>> {
let block = SERVICES
.block
.by_id
.get(&id)?;
async fn get_block(Path(id): Path<BlockHash>) -> Result<Json<Option<Block>>> {
let block = SERVICES.block.by_id.get(&id)?;

Ok(Json(block))
}
Expand Down
8 changes: 4 additions & 4 deletions lib/ain-ocean/src/api/loan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ use bitcoin::Txid;
use log::debug;

use crate::{
api_paged_response::ApiPagedResponse, api_query::PaginationQuery, error::OceanResult,
model::VaultAuctionBatchHistory, repository::RepositoryOps, SERVICES,
api_paged_response::ApiPagedResponse, api_query::PaginationQuery,
model::VaultAuctionBatchHistory, repository::RepositoryOps, Result, SERVICES,
};

async fn list_scheme() -> String {
Expand Down Expand Up @@ -46,7 +46,7 @@ async fn get_vault(Path(vault_id): Path<String>) -> String {
async fn list_vault_auction_history(
Path((vault_id, height, batch_index)): Path<(Txid, u32, u32)>,
Query(query): Query<PaginationQuery>,
) -> OceanResult<Json<ApiPagedResponse<VaultAuctionBatchHistory>>> {
) -> Result<Json<ApiPagedResponse<VaultAuctionBatchHistory>>> {
println!("listvault auction history");
debug!(
"Auction history for vault id {}, height {}, batch index {}",
Expand Down Expand Up @@ -92,7 +92,7 @@ async fn list_vault_auction_history(

Ok(auction)
})
.collect::<OceanResult<Vec<_>>>()?;
.collect::<Result<Vec<_>>>()?;

Ok(Json(ApiPagedResponse::of(
auctions,
Expand Down
12 changes: 5 additions & 7 deletions lib/ain-ocean/src/api/masternode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ use bitcoin::Txid;
use serde::{Deserialize, Serialize};

use crate::{
api_paged_response::ApiPagedResponse, api_query::PaginationQuery, error::OceanResult,
model::Masternode, repository::RepositoryOps, SERVICES,
api_paged_response::ApiPagedResponse, api_query::PaginationQuery, model::Masternode,
repository::RepositoryOps, Result, SERVICES,
};

#[derive(Serialize, Deserialize, Debug, Default, Clone)]
Expand Down Expand Up @@ -89,7 +89,7 @@ impl From<Masternode> for MasternodeData {

async fn list_masternodes(
Query(query): Query<PaginationQuery>,
) -> OceanResult<Json<ApiPagedResponse<MasternodeData>>> {
) -> Result<Json<ApiPagedResponse<MasternodeData>>> {
let next = query
.next
.map(|q| {
Expand Down Expand Up @@ -120,7 +120,7 @@ async fn list_masternodes(

Ok(mn.into())
})
.collect::<OceanResult<Vec<_>>>()?;
.collect::<Result<Vec<_>>>()?;

Ok(Json(ApiPagedResponse::of(
masternodes,
Expand All @@ -129,9 +129,7 @@ async fn list_masternodes(
)))
}

async fn get_masternode(
Path(masternode_id): Path<Txid>,
) -> OceanResult<Json<Option<MasternodeData>>> {
async fn get_masternode(Path(masternode_id): Path<Txid>) -> Result<Json<Option<MasternodeData>>> {
let mn = SERVICES
.masternode
.by_id
Expand Down
119 changes: 111 additions & 8 deletions lib/ain-ocean/src/api/poolpairs.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
use axum::{
extract::{Path, Query},
routing::get,
Router,
Json, Router,
};
use log::debug;
use serde::{Deserialize, Serialize};

use crate::{
api_paged_response::ApiPagedResponse,
api_query::PaginationQuery,
model::{BlockContext, PoolSwap},
repository::RepositoryOps,
Result, SERVICES,
};
use serde::Deserialize;

#[derive(Deserialize)]
struct PoolPair {
Expand Down Expand Up @@ -32,6 +41,57 @@ struct DexPrices {
denomination: Option<String>,
}

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

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct PoolSwapData {
id: String,
sort: String,
txid: String,
txno: usize,
pool_pair_id: String,
from_amount: String,
from_token_id: u64,
block: BlockContext,
from: PoolSwapFromToData,
to: PoolSwapFromToData,
}

impl From<PoolSwap> for PoolSwapData {
fn from(v: PoolSwap) -> 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_token_id: v.from_token_id,
from: PoolSwapFromToData {
address: v.from.to_hex_string(),
amount: v.from_amount.to_string(),
// symbol: todo!(),
// display_symbol: todo!(),
},
to: PoolSwapFromToData {
address: v.to.to_hex_string(),
amount: v.to_amount.to_string(),
// symbol: todo!(),
// display_symbol: todo!(),
},
block: v.block,
}
}
}

async fn list_poolpairs() -> String {
"List of poolpairs".to_string()
}
Expand All @@ -40,12 +100,55 @@ async fn get_poolpair(Path(PoolPair { id }): Path<PoolPair>) -> String {
format!("Details of poolpair with id {}", id)
}

async fn list_pool_swaps(Path(PoolPair { id }): Path<PoolPair>) -> String {
format!("List of swaps for poolpair {}", id)
}
// Use single method for now since additional verbose keys are indexed
// TODO: assess need for additional verbose method
async fn list_pool_swaps(
Path(id): Path<u32>,
Query(query): Query<PaginationQuery>,
) -> Result<Json<ApiPagedResponse<PoolSwapData>>> {
debug!("list_pool_swaps for id {id}",);
let next = query
.next
.map(|q| {
let parts: Vec<&str> = q.split('-').collect();
if parts.len() != 2 {
return Err("Invalid query format");
}

let height = parts[0].parse::<u32>().map_err(|_| "Invalid height")?;
let txno = parts[1].parse::<usize>().map_err(|_| "Invalid txno")?;

Ok((height, txno))
})
.transpose()?
.unwrap_or_default();

debug!("next : {:?}", next);

let size = if query.size > 0 && query.size < 20 {
query.size
} else {
20
};

let swaps = SERVICES
.pool
.by_id
.list(Some((id, next.0, next.1)))?
.take(size)
.take_while(|item| match item {
Ok((k, _)) => k.0 == id,
_ => true,
})
.map(|item| {
let (_, swap) = item?;
Ok(PoolSwapData::from(swap))
})
.collect::<Result<Vec<_>>>()?;

async fn list_pool_swaps_verbose(Path(PoolPair { id }): Path<PoolPair>) -> String {
format!("Verbose list of swaps for poolpair {}", id)
Ok(Json(ApiPagedResponse::of(swaps, query.size, |swap| {
swap.sort.to_string()
})))
}

async fn list_pool_swap_aggregates(
Expand Down Expand Up @@ -94,7 +197,7 @@ pub fn router() -> Router {
.route("/", get(list_poolpairs))
.route("/:id", get(get_poolpair))
.route("/:id/swaps", get(list_pool_swaps))
.route("/:id/swaps/verbose", get(list_pool_swaps_verbose))
.route("/:id/swaps/verbose", get(list_pool_swaps))
.route(
"/:id/swaps/aggregate/:interval",
get(list_pool_swap_aggregates),
Expand Down
9 changes: 7 additions & 2 deletions lib/ain-ocean/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
use std::num::ParseIntError;

use ain_db::DBError;
use anyhow::format_err;
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
use bitcoin::hex::HexToArrayError;
use thiserror::Error;
pub type OceanResult<T> = Result<T, OceanError>;
use anyhow::format_err;

#[derive(Error, Debug)]
pub enum OceanError {
Expand All @@ -18,6 +17,12 @@ pub enum OceanError {
ParseIntError(#[from] ParseIntError),
#[error("Ocean: DBError error: {0:?}")]
DBError(#[from] DBError),
#[error("Ocean: IO error: {0:?}")]
IOError(#[from] std::io::Error),
#[error("Ocean: FromHexError error: {0:?}")]
FromHexError(#[from] hex::FromHexError),
#[error("Ocean: Consensus encode error: {0:?}")]
ConsensusEncodeError(#[from] bitcoin::consensus::encode::Error),
#[error(transparent)]
Other(#[from] anyhow::Error),
}
Expand Down
27 changes: 13 additions & 14 deletions lib/ain-ocean/src/indexer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,22 @@ mod auction;
mod masternode;
mod oracle;
mod pool;
pub mod tx_result;

use dftx_rs::Transaction;

pub(crate) trait Index {
fn index(&self, ctx: &BlockContext, tx: Transaction, idx: usize) -> Result<()>;
fn invalidate(&self, context: &BlockContext, tx: Transaction, idx: usize) -> Result<()>;
}

use dftx_rs::{deserialize, Block, DfTx};
use dftx_rs::{deserialize, Block, DfTx, Transaction};
use log::debug;

use crate::{
model::{BlockContext, Block as BlockMapper},
model::{Block as BlockMapper, BlockContext},
repository::RepositoryOps,
Result,
SERVICES,
Result, SERVICES,
};

pub(crate) trait Index {
fn index(&self, ctx: &BlockContext, tx: Transaction, idx: usize) -> Result<()>;
fn invalidate(&self, context: &BlockContext, tx: Transaction, idx: usize) -> Result<()>;
}

pub struct BlockV2Info {
pub height: u32,
pub difficulty: u32,
Expand Down Expand Up @@ -68,7 +66,7 @@ pub fn index_block(encoded_block: String, info: &BlockV2Info) -> Result<()> {
weight: info.weight,
};

SERVICES.block.raw.put(&ctx.hash, &encoded_block)?;
SERVICES.block.raw.put(&ctx.hash, &encoded_block)?;
SERVICES.block.by_id.put(&ctx.hash, &block_mapper)?;
SERVICES.block.by_height.put(&ctx.height, &block_hash)?;

Expand All @@ -84,6 +82,7 @@ pub fn index_block(encoded_block: String, info: &BlockV2Info) -> Result<()> {

let raw_tx = &bytes[offset..];
let dftx = deserialize::<DfTx>(raw_tx)?;
debug!("dftx : {:?}", dftx);
match dftx {
DfTx::CreateMasternode(data) => data.index(&ctx, tx, idx)?,
DfTx::UpdateMasternode(data) => data.index(&ctx, tx, idx)?,
Expand All @@ -92,8 +91,8 @@ pub fn index_block(encoded_block: String, info: &BlockV2Info) -> Result<()> {
// DfTx::RemoveOracle(data) => data.index(&ctx, tx, idx)?,
// DfTx::UpdateOracle(data) => data.index(&ctx, tx, idx)?,
// DfTx::SetOracleData(data) => data.index(&ctx, tx, idx)?,
// DfTx::PoolSwap(data) => data.index(&ctx, tx, idx)?,
// DfTx::CompositeSwap(data) => data.index(&ctx, tx, idx)?,
DfTx::PoolSwap(data) => data.index(&ctx, tx, idx)?,
DfTx::CompositeSwap(data) => data.index(&ctx, tx, idx)?,
DfTx::PlaceAuctionBid(data) => data.index(&ctx, tx, idx)?,
_ => (),
}
Expand Down
Loading

0 comments on commit ce29359

Please sign in to comment.