Skip to content

Commit

Permalink
balance endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
leecchh committed Dec 4, 2024
1 parent aaf9347 commit 9911f6f
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 4 deletions.
14 changes: 11 additions & 3 deletions crates/sui-deepbook-indexer/src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
// SPDX-License-Identifier: Apache-2.0

use diesel::data_types::PgTimestamp;
use diesel::{Identifiable, Insertable, Queryable, Selectable};
use diesel::{Identifiable, Insertable, Queryable, QueryableByName, Selectable};

use serde::Serialize;
use sui_indexer_builder::{Task, LIVE_TASK_TARGET_CHECKPOINT};

use crate::schema::{
balances, flashloans, order_fills, order_updates, pool_prices, pools, progress_store,
proposals, rebates, stakes, sui_error_transactions, trade_params_update, votes,
balances, balances_summary, flashloans, order_fills, order_updates, pool_prices, pools,
progress_store, proposals, rebates, stakes, sui_error_transactions, trade_params_update, votes,
};

#[derive(Queryable, Selectable, Insertable, Identifiable, Debug)]
Expand Down Expand Up @@ -70,6 +70,14 @@ pub struct OrderFillSummary {
pub quantity: i64,
}

#[derive(QueryableByName, Debug, Serialize)]
#[diesel(table_name = balances_summary)]
pub struct BalancesSummary {
pub asset: String,
pub amount: i64,
pub deposit: bool,
}

#[derive(Queryable, Selectable, Insertable, Identifiable, Debug)]
#[diesel(table_name = flashloans, primary_key(event_digest))]
pub struct Flashloan {
Expand Down
8 changes: 8 additions & 0 deletions crates/sui-deepbook-indexer/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,3 +240,11 @@ diesel::allow_tables_to_appear_in_same_query!(
trade_params_update,
votes,
);

diesel::table! {
balances_summary (asset) {
asset -> Text,
amount -> Int8,
deposit -> Bool,
}
}
43 changes: 42 additions & 1 deletion crates/sui-deepbook-indexer/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

use crate::{
error::DeepBookError,
models::{OrderFillSummary, Pools},
models::{BalancesSummary, OrderFillSummary, Pools},
schema::{self},
sui_deepbook_indexer::PgDeepbookPersistent,
};
Expand Down Expand Up @@ -42,6 +42,7 @@ pub const GET_HISTORICAL_VOLUME_BY_BALANCE_MANAGER_ID: &str =
"/get_historical_volume_by_balance_manager_id/:pool_ids/:balance_manager_id";
pub const HISTORICAL_VOLUME_PATH: &str = "/historical_volume/:pool_names";
pub const ALL_HISTORICAL_VOLUME_PATH: &str = "/all_historical_volume";
pub const GET_NET_DEPOSITS: &str = "/get_net_deposits/:asset_ids/:timestamp";
pub const LEVEL2_PATH: &str = "/orderbook/:pool_name";
pub const LEVEL2_MODULE: &str = "pool";
pub const LEVEL2_FUNCTION: &str = "get_level2_ticks_from_mid";
Expand Down Expand Up @@ -70,6 +71,7 @@ pub(crate) fn make_router(state: PgDeepbookPersistent) -> Router {
get(get_historical_volume_by_balance_manager_id),
)
.route(LEVEL2_PATH, get(orderbook))
.route(GET_NET_DEPOSITS, get(get_net_deposits))
.with_state(state)
}

Expand Down Expand Up @@ -613,6 +615,45 @@ async fn orderbook(
Ok(Json(result))
}

async fn get_net_deposits(
Path((asset_ids, timestamp)): Path<(String, String)>,
State(state): State<PgDeepbookPersistent>,
) -> Result<Json<HashMap<String, i64>>, DeepBookError> {
let connection = &mut state.pool.get().await?;
let mut query =
"SELECT asset, SUM(amount)::bigint AS amount, deposit FROM balances WHERE checkpoint_timestamp_ms < "
.to_string();
query.push_str(&timestamp);
query.push_str("000 AND asset in (");
for asset in asset_ids.split(",") {
if asset.starts_with("0x") {
let len = asset.len();
query.push_str(&format!("'{}',", &asset[2..len]));
} else {
query.push_str(&format!("'{}',", asset));
}
}
query.pop();
query.push_str(") GROUP BY asset, deposit");

let results: Vec<BalancesSummary> = diesel::sql_query(query).load(connection).await?;
let mut net_deposits = HashMap::new();
for result in results {
let mut asset = result.asset;
if !asset.starts_with("0x") {
asset.insert_str(0, "0x");
}
let amount = result.amount;
if result.deposit {
*net_deposits.entry(asset).or_insert(0) += amount;
} else {
*net_deposits.entry(asset).or_insert(0) -= amount;
}
}

Ok(Json(net_deposits))
}

fn parse_type_input(type_str: &str) -> Result<TypeInput, DeepBookError> {
let type_tag = TypeTag::from_str(type_str)?;
Ok(TypeInput::from(type_tag))
Expand Down

0 comments on commit 9911f6f

Please sign in to comment.