Skip to content

Commit ce29359

Browse files
authored
Index swap and swap result (#2778)
1 parent 24e2997 commit ce29359

26 files changed

Lines changed: 596 additions & 252 deletions

File tree

lib/Cargo.lock

Lines changed: 141 additions & 146 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

lib/ain-ocean/src/api/block.rs

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,13 @@ use axum::{
66
use bitcoin::BlockHash;
77

88
use crate::{
9-
api_paged_response::ApiPagedResponse,
10-
api_query::PaginationQuery,
11-
error::OceanResult,
12-
SERVICES,
13-
repository::RepositoryOps,
14-
model::Block,
9+
api_paged_response::ApiPagedResponse, api_query::PaginationQuery, model::Block,
10+
repository::RepositoryOps, Result, SERVICES,
1511
};
1612

1713
async fn list_blocks(
1814
Query(query): Query<PaginationQuery>,
19-
) -> OceanResult<Json<ApiPagedResponse<Block>>> {
15+
) -> Result<Json<ApiPagedResponse<Block>>> {
2016
let blocks = SERVICES
2117
.block
2218
.by_height
@@ -32,20 +28,15 @@ async fn list_blocks(
3228

3329
Ok(b)
3430
})
35-
.collect::<OceanResult<Vec<_>>>()?;
31+
.collect::<Result<Vec<_>>>()?;
3632

37-
Ok(Json(ApiPagedResponse::of(
38-
blocks,
39-
query.size,
40-
|block| block.clone().id,
41-
)))
33+
Ok(Json(ApiPagedResponse::of(blocks, query.size, |block| {
34+
block.clone().id
35+
})))
4236
}
4337

44-
async fn get_block(Path(id): Path<BlockHash>) -> OceanResult<Json<Option<Block>>> {
45-
let block = SERVICES
46-
.block
47-
.by_id
48-
.get(&id)?;
38+
async fn get_block(Path(id): Path<BlockHash>) -> Result<Json<Option<Block>>> {
39+
let block = SERVICES.block.by_id.get(&id)?;
4940

5041
Ok(Json(block))
5142
}

lib/ain-ocean/src/api/loan.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ use bitcoin::Txid;
77
use log::debug;
88

99
use crate::{
10-
api_paged_response::ApiPagedResponse, api_query::PaginationQuery, error::OceanResult,
11-
model::VaultAuctionBatchHistory, repository::RepositoryOps, SERVICES,
10+
api_paged_response::ApiPagedResponse, api_query::PaginationQuery,
11+
model::VaultAuctionBatchHistory, repository::RepositoryOps, Result, SERVICES,
1212
};
1313

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

9393
Ok(auction)
9494
})
95-
.collect::<OceanResult<Vec<_>>>()?;
95+
.collect::<Result<Vec<_>>>()?;
9696

9797
Ok(Json(ApiPagedResponse::of(
9898
auctions,

lib/ain-ocean/src/api/masternode.rs

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ use bitcoin::Txid;
77
use serde::{Deserialize, Serialize};
88

99
use crate::{
10-
api_paged_response::ApiPagedResponse, api_query::PaginationQuery, error::OceanResult,
11-
model::Masternode, repository::RepositoryOps, SERVICES,
10+
api_paged_response::ApiPagedResponse, api_query::PaginationQuery, model::Masternode,
11+
repository::RepositoryOps, Result, SERVICES,
1212
};
1313

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

9090
async fn list_masternodes(
9191
Query(query): Query<PaginationQuery>,
92-
) -> OceanResult<Json<ApiPagedResponse<MasternodeData>>> {
92+
) -> Result<Json<ApiPagedResponse<MasternodeData>>> {
9393
let next = query
9494
.next
9595
.map(|q| {
@@ -120,7 +120,7 @@ async fn list_masternodes(
120120

121121
Ok(mn.into())
122122
})
123-
.collect::<OceanResult<Vec<_>>>()?;
123+
.collect::<Result<Vec<_>>>()?;
124124

125125
Ok(Json(ApiPagedResponse::of(
126126
masternodes,
@@ -129,9 +129,7 @@ async fn list_masternodes(
129129
)))
130130
}
131131

132-
async fn get_masternode(
133-
Path(masternode_id): Path<Txid>,
134-
) -> OceanResult<Json<Option<MasternodeData>>> {
132+
async fn get_masternode(Path(masternode_id): Path<Txid>) -> Result<Json<Option<MasternodeData>>> {
135133
let mn = SERVICES
136134
.masternode
137135
.by_id

lib/ain-ocean/src/api/poolpairs.rs

Lines changed: 111 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,18 @@
11
use axum::{
22
extract::{Path, Query},
33
routing::get,
4-
Router,
4+
Json, Router,
5+
};
6+
use log::debug;
7+
use serde::{Deserialize, Serialize};
8+
9+
use crate::{
10+
api_paged_response::ApiPagedResponse,
11+
api_query::PaginationQuery,
12+
model::{BlockContext, PoolSwap},
13+
repository::RepositoryOps,
14+
Result, SERVICES,
515
};
6-
use serde::Deserialize;
716

817
#[derive(Deserialize)]
918
struct PoolPair {
@@ -32,6 +41,57 @@ struct DexPrices {
3241
denomination: Option<String>,
3342
}
3443

44+
#[derive(Serialize, Deserialize, Debug, Clone)]
45+
#[serde(rename_all = "camelCase")]
46+
pub struct PoolSwapFromToData {
47+
address: String,
48+
amount: String,
49+
// symbol: String,
50+
// display_symbol: String,
51+
}
52+
53+
#[derive(Serialize, Deserialize, Debug, Clone)]
54+
#[serde(rename_all = "camelCase")]
55+
pub struct PoolSwapData {
56+
id: String,
57+
sort: String,
58+
txid: String,
59+
txno: usize,
60+
pool_pair_id: String,
61+
from_amount: String,
62+
from_token_id: u64,
63+
block: BlockContext,
64+
from: PoolSwapFromToData,
65+
to: PoolSwapFromToData,
66+
}
67+
68+
impl From<PoolSwap> for PoolSwapData {
69+
fn from(v: PoolSwap) -> Self {
70+
Self {
71+
id: v.id,
72+
sort: v.sort,
73+
txid: v.txid.to_string(),
74+
txno: v.txno,
75+
pool_pair_id: v.pool_id.to_string(),
76+
from_amount: v.from_amount.to_string(),
77+
from_token_id: v.from_token_id,
78+
from: PoolSwapFromToData {
79+
address: v.from.to_hex_string(),
80+
amount: v.from_amount.to_string(),
81+
// symbol: todo!(),
82+
// display_symbol: todo!(),
83+
},
84+
to: PoolSwapFromToData {
85+
address: v.to.to_hex_string(),
86+
amount: v.to_amount.to_string(),
87+
// symbol: todo!(),
88+
// display_symbol: todo!(),
89+
},
90+
block: v.block,
91+
}
92+
}
93+
}
94+
3595
async fn list_poolpairs() -> String {
3696
"List of poolpairs".to_string()
3797
}
@@ -40,12 +100,55 @@ async fn get_poolpair(Path(PoolPair { id }): Path<PoolPair>) -> String {
40100
format!("Details of poolpair with id {}", id)
41101
}
42102

43-
async fn list_pool_swaps(Path(PoolPair { id }): Path<PoolPair>) -> String {
44-
format!("List of swaps for poolpair {}", id)
45-
}
103+
// Use single method for now since additional verbose keys are indexed
104+
// TODO: assess need for additional verbose method
105+
async fn list_pool_swaps(
106+
Path(id): Path<u32>,
107+
Query(query): Query<PaginationQuery>,
108+
) -> Result<Json<ApiPagedResponse<PoolSwapData>>> {
109+
debug!("list_pool_swaps for id {id}",);
110+
let next = query
111+
.next
112+
.map(|q| {
113+
let parts: Vec<&str> = q.split('-').collect();
114+
if parts.len() != 2 {
115+
return Err("Invalid query format");
116+
}
117+
118+
let height = parts[0].parse::<u32>().map_err(|_| "Invalid height")?;
119+
let txno = parts[1].parse::<usize>().map_err(|_| "Invalid txno")?;
120+
121+
Ok((height, txno))
122+
})
123+
.transpose()?
124+
.unwrap_or_default();
125+
126+
debug!("next : {:?}", next);
127+
128+
let size = if query.size > 0 && query.size < 20 {
129+
query.size
130+
} else {
131+
20
132+
};
133+
134+
let swaps = SERVICES
135+
.pool
136+
.by_id
137+
.list(Some((id, next.0, next.1)))?
138+
.take(size)
139+
.take_while(|item| match item {
140+
Ok((k, _)) => k.0 == id,
141+
_ => true,
142+
})
143+
.map(|item| {
144+
let (_, swap) = item?;
145+
Ok(PoolSwapData::from(swap))
146+
})
147+
.collect::<Result<Vec<_>>>()?;
46148

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

51154
async fn list_pool_swap_aggregates(
@@ -94,7 +197,7 @@ pub fn router() -> Router {
94197
.route("/", get(list_poolpairs))
95198
.route("/:id", get(get_poolpair))
96199
.route("/:id/swaps", get(list_pool_swaps))
97-
.route("/:id/swaps/verbose", get(list_pool_swaps_verbose))
200+
.route("/:id/swaps/verbose", get(list_pool_swaps))
98201
.route(
99202
"/:id/swaps/aggregate/:interval",
100203
get(list_pool_swap_aggregates),

lib/ain-ocean/src/error.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
use std::num::ParseIntError;
22

33
use ain_db::DBError;
4+
use anyhow::format_err;
45
use axum::{
56
http::StatusCode,
67
response::{IntoResponse, Response},
78
};
89
use bitcoin::hex::HexToArrayError;
910
use thiserror::Error;
10-
pub type OceanResult<T> = Result<T, OceanError>;
11-
use anyhow::format_err;
1211

1312
#[derive(Error, Debug)]
1413
pub enum OceanError {
@@ -18,6 +17,12 @@ pub enum OceanError {
1817
ParseIntError(#[from] ParseIntError),
1918
#[error("Ocean: DBError error: {0:?}")]
2019
DBError(#[from] DBError),
20+
#[error("Ocean: IO error: {0:?}")]
21+
IOError(#[from] std::io::Error),
22+
#[error("Ocean: FromHexError error: {0:?}")]
23+
FromHexError(#[from] hex::FromHexError),
24+
#[error("Ocean: Consensus encode error: {0:?}")]
25+
ConsensusEncodeError(#[from] bitcoin::consensus::encode::Error),
2126
#[error(transparent)]
2227
Other(#[from] anyhow::Error),
2328
}

lib/ain-ocean/src/indexer/mod.rs

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,22 @@ mod auction;
22
mod masternode;
33
mod oracle;
44
mod pool;
5+
pub mod tx_result;
56

6-
use dftx_rs::Transaction;
7-
8-
pub(crate) trait Index {
9-
fn index(&self, ctx: &BlockContext, tx: Transaction, idx: usize) -> Result<()>;
10-
fn invalidate(&self, context: &BlockContext, tx: Transaction, idx: usize) -> Result<()>;
11-
}
12-
13-
use dftx_rs::{deserialize, Block, DfTx};
7+
use dftx_rs::{deserialize, Block, DfTx, Transaction};
148
use log::debug;
159

1610
use crate::{
17-
model::{BlockContext, Block as BlockMapper},
11+
model::{Block as BlockMapper, BlockContext},
1812
repository::RepositoryOps,
19-
Result,
20-
SERVICES,
13+
Result, SERVICES,
2114
};
2215

16+
pub(crate) trait Index {
17+
fn index(&self, ctx: &BlockContext, tx: Transaction, idx: usize) -> Result<()>;
18+
fn invalidate(&self, context: &BlockContext, tx: Transaction, idx: usize) -> Result<()>;
19+
}
20+
2321
pub struct BlockV2Info {
2422
pub height: u32,
2523
pub difficulty: u32,
@@ -68,7 +66,7 @@ pub fn index_block(encoded_block: String, info: &BlockV2Info) -> Result<()> {
6866
weight: info.weight,
6967
};
7068

71-
SERVICES.block.raw.put(&ctx.hash, &encoded_block)?;
69+
SERVICES.block.raw.put(&ctx.hash, &encoded_block)?;
7270
SERVICES.block.by_id.put(&ctx.hash, &block_mapper)?;
7371
SERVICES.block.by_height.put(&ctx.height, &block_hash)?;
7472

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

8583
let raw_tx = &bytes[offset..];
8684
let dftx = deserialize::<DfTx>(raw_tx)?;
85+
debug!("dftx : {:?}", dftx);
8786
match dftx {
8887
DfTx::CreateMasternode(data) => data.index(&ctx, tx, idx)?,
8988
DfTx::UpdateMasternode(data) => data.index(&ctx, tx, idx)?,
@@ -92,8 +91,8 @@ pub fn index_block(encoded_block: String, info: &BlockV2Info) -> Result<()> {
9291
// DfTx::RemoveOracle(data) => data.index(&ctx, tx, idx)?,
9392
// DfTx::UpdateOracle(data) => data.index(&ctx, tx, idx)?,
9493
// DfTx::SetOracleData(data) => data.index(&ctx, tx, idx)?,
95-
// DfTx::PoolSwap(data) => data.index(&ctx, tx, idx)?,
96-
// DfTx::CompositeSwap(data) => data.index(&ctx, tx, idx)?,
94+
DfTx::PoolSwap(data) => data.index(&ctx, tx, idx)?,
95+
DfTx::CompositeSwap(data) => data.index(&ctx, tx, idx)?,
9796
DfTx::PlaceAuctionBid(data) => data.index(&ctx, tx, idx)?,
9897
_ => (),
9998
}

0 commit comments

Comments
 (0)