0.7.16
This commit is contained in:
@@ -19,6 +19,7 @@ mod liquidity_event;
|
||||
mod observed_token;
|
||||
mod onchain_observation;
|
||||
mod pair;
|
||||
mod pair_metric;
|
||||
mod pool;
|
||||
mod pool_listing;
|
||||
mod pool_origin;
|
||||
@@ -27,6 +28,7 @@ mod swap;
|
||||
mod token;
|
||||
mod token_burn_event;
|
||||
mod token_mint_event;
|
||||
mod trade_event;
|
||||
mod wallet;
|
||||
mod wallet_participation;
|
||||
|
||||
@@ -47,6 +49,7 @@ pub use liquidity_event::KbLiquidityEventDto;
|
||||
pub use observed_token::KbObservedTokenDto;
|
||||
pub use onchain_observation::KbOnchainObservationDto;
|
||||
pub use pair::KbPairDto;
|
||||
pub use pair_metric::KbPairMetricDto;
|
||||
pub use pool::KbPoolDto;
|
||||
pub use pool_listing::KbPoolListingDto;
|
||||
pub use pool_origin::KbPoolOriginDto;
|
||||
@@ -55,5 +58,6 @@ pub use swap::KbSwapDto;
|
||||
pub use token::KbTokenDto;
|
||||
pub use token_burn_event::KbTokenBurnEventDto;
|
||||
pub use token_mint_event::KbTokenMintEventDto;
|
||||
pub use trade_event::KbTradeEventDto;
|
||||
pub use wallet::KbWalletDto;
|
||||
pub use wallet_participation::KbWalletParticipationDto;
|
||||
|
||||
102
kb_lib/src/db/dtos/pair_metric.rs
Normal file
102
kb_lib/src/db/dtos/pair_metric.rs
Normal file
@@ -0,0 +1,102 @@
|
||||
// file: kb_lib/src/db/dtos/pair_metric.rs
|
||||
|
||||
//! Pair-metric DTO.
|
||||
|
||||
/// Application-facing pair-metric DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbPairMetricDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Related pair id.
|
||||
pub pair_id: i64,
|
||||
/// Optional first observed slot.
|
||||
pub first_slot: std::option::Option<i64>,
|
||||
/// Optional last observed slot.
|
||||
pub last_slot: std::option::Option<i64>,
|
||||
/// Optional first observed signature.
|
||||
pub first_signature: std::option::Option<std::string::String>,
|
||||
/// Optional last observed signature.
|
||||
pub last_signature: std::option::Option<std::string::String>,
|
||||
/// Total trade count.
|
||||
pub trade_count: i64,
|
||||
/// Total buy count.
|
||||
pub buy_count: i64,
|
||||
/// Total sell count.
|
||||
pub sell_count: i64,
|
||||
/// Optional cumulative raw base volume.
|
||||
pub cumulative_base_amount_raw: std::option::Option<std::string::String>,
|
||||
/// Optional cumulative raw quote volume.
|
||||
pub cumulative_quote_amount_raw: std::option::Option<std::string::String>,
|
||||
/// Optional last derived quote-per-base price.
|
||||
pub last_price_quote_per_base: std::option::Option<f64>,
|
||||
/// Creation timestamp.
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbPairMetricDto {
|
||||
/// Creates a new pair-metric DTO.
|
||||
pub fn new(pair_id: i64) -> Self {
|
||||
let now = chrono::Utc::now();
|
||||
Self {
|
||||
id: None,
|
||||
pair_id,
|
||||
first_slot: None,
|
||||
last_slot: None,
|
||||
first_signature: None,
|
||||
last_signature: None,
|
||||
trade_count: 0,
|
||||
buy_count: 0,
|
||||
sell_count: 0,
|
||||
cumulative_base_amount_raw: None,
|
||||
cumulative_quote_amount_raw: None,
|
||||
last_price_quote_per_base: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbPairMetricEntity> for KbPairMetricDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbPairMetricEntity) -> Result<Self, Self::Error> {
|
||||
let created_at_result = chrono::DateTime::parse_from_rfc3339(&entity.created_at);
|
||||
let created_at = match created_at_result {
|
||||
Ok(created_at) => created_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse pair_metric created_at '{}': {}",
|
||||
entity.created_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse pair_metric updated_at '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
pair_id: entity.pair_id,
|
||||
first_slot: entity.first_slot,
|
||||
last_slot: entity.last_slot,
|
||||
first_signature: entity.first_signature,
|
||||
last_signature: entity.last_signature,
|
||||
trade_count: entity.trade_count,
|
||||
buy_count: entity.buy_count,
|
||||
sell_count: entity.sell_count,
|
||||
cumulative_base_amount_raw: entity.cumulative_base_amount_raw,
|
||||
cumulative_quote_amount_raw: entity.cumulative_quote_amount_raw,
|
||||
last_price_quote_per_base: entity.last_price_quote_per_base,
|
||||
created_at,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
153
kb_lib/src/db/dtos/trade_event.rs
Normal file
153
kb_lib/src/db/dtos/trade_event.rs
Normal file
@@ -0,0 +1,153 @@
|
||||
// file: kb_lib/src/db/dtos/trade_event.rs
|
||||
|
||||
//! Trade-event DTO.
|
||||
|
||||
/// Application-facing trade-event DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbTradeEventDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Related DEX id.
|
||||
pub dex_id: i64,
|
||||
/// Related pool id.
|
||||
pub pool_id: i64,
|
||||
/// Related pair id.
|
||||
pub pair_id: i64,
|
||||
/// Related transaction id.
|
||||
pub transaction_id: i64,
|
||||
/// Related decoded event id.
|
||||
pub decoded_event_id: i64,
|
||||
/// Related transaction signature.
|
||||
pub signature: std::string::String,
|
||||
/// Optional observed slot.
|
||||
pub slot: std::option::Option<i64>,
|
||||
/// Stable trade side.
|
||||
pub trade_side: crate::KbSwapTradeSide,
|
||||
/// Related base token id.
|
||||
pub base_token_id: i64,
|
||||
/// Related quote token id.
|
||||
pub quote_token_id: i64,
|
||||
/// Optional raw base amount.
|
||||
pub base_amount_raw: std::option::Option<std::string::String>,
|
||||
/// Optional raw quote amount.
|
||||
pub quote_amount_raw: std::option::Option<std::string::String>,
|
||||
/// Optional derived quote-per-base price.
|
||||
pub price_quote_per_base: std::option::Option<f64>,
|
||||
/// Observation source kind.
|
||||
pub source_kind: crate::KbObservationSourceKind,
|
||||
/// Optional logical source endpoint name.
|
||||
pub source_endpoint_name: std::option::Option<std::string::String>,
|
||||
/// Persisted payload JSON.
|
||||
pub payload_json: std::string::String,
|
||||
/// Creation timestamp.
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbTradeEventDto {
|
||||
/// Creates a new trade-event DTO.
|
||||
pub fn new(
|
||||
dex_id: i64,
|
||||
pool_id: i64,
|
||||
pair_id: i64,
|
||||
transaction_id: i64,
|
||||
decoded_event_id: i64,
|
||||
signature: std::string::String,
|
||||
slot: std::option::Option<i64>,
|
||||
trade_side: crate::KbSwapTradeSide,
|
||||
base_token_id: i64,
|
||||
quote_token_id: i64,
|
||||
base_amount_raw: std::option::Option<std::string::String>,
|
||||
quote_amount_raw: std::option::Option<std::string::String>,
|
||||
price_quote_per_base: std::option::Option<f64>,
|
||||
source_kind: crate::KbObservationSourceKind,
|
||||
source_endpoint_name: std::option::Option<std::string::String>,
|
||||
payload_json: std::string::String,
|
||||
) -> Self {
|
||||
let now = chrono::Utc::now();
|
||||
Self {
|
||||
id: None,
|
||||
dex_id,
|
||||
pool_id,
|
||||
pair_id,
|
||||
transaction_id,
|
||||
decoded_event_id,
|
||||
signature,
|
||||
slot,
|
||||
trade_side,
|
||||
base_token_id,
|
||||
quote_token_id,
|
||||
base_amount_raw,
|
||||
quote_amount_raw,
|
||||
price_quote_per_base,
|
||||
source_kind,
|
||||
source_endpoint_name,
|
||||
payload_json,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbTradeEventEntity> for KbTradeEventDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbTradeEventEntity) -> Result<Self, Self::Error> {
|
||||
let trade_side = kb_trade_side_from_string(entity.trade_side.as_str());
|
||||
let source_kind_result = crate::KbObservationSourceKind::from_i16(entity.source_kind);
|
||||
let source_kind = match source_kind_result {
|
||||
Ok(source_kind) => source_kind,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let created_at_result = chrono::DateTime::parse_from_rfc3339(&entity.created_at);
|
||||
let created_at = match created_at_result {
|
||||
Ok(created_at) => created_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse trade_event created_at '{}': {}",
|
||||
entity.created_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse trade_event updated_at '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
dex_id: entity.dex_id,
|
||||
pool_id: entity.pool_id,
|
||||
pair_id: entity.pair_id,
|
||||
transaction_id: entity.transaction_id,
|
||||
decoded_event_id: entity.decoded_event_id,
|
||||
signature: entity.signature,
|
||||
slot: entity.slot,
|
||||
trade_side,
|
||||
base_token_id: entity.base_token_id,
|
||||
quote_token_id: entity.quote_token_id,
|
||||
base_amount_raw: entity.base_amount_raw,
|
||||
quote_amount_raw: entity.quote_amount_raw,
|
||||
price_quote_per_base: entity.price_quote_per_base,
|
||||
source_kind,
|
||||
source_endpoint_name: entity.source_endpoint_name,
|
||||
payload_json: entity.payload_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn kb_trade_side_from_string(value: &str) -> crate::KbSwapTradeSide {
|
||||
match value {
|
||||
"BuyBase" => crate::KbSwapTradeSide::BuyBase,
|
||||
"SellBase" => crate::KbSwapTradeSide::SellBase,
|
||||
_ => crate::KbSwapTradeSide::Unknown,
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ mod liquidity_event;
|
||||
mod observed_token;
|
||||
mod onchain_observation;
|
||||
mod pair;
|
||||
mod pair_metric;
|
||||
mod pool;
|
||||
mod pool_listing;
|
||||
mod pool_origin;
|
||||
@@ -29,6 +30,7 @@ mod swap;
|
||||
mod token;
|
||||
mod token_burn_event;
|
||||
mod token_mint_event;
|
||||
mod trade_event;
|
||||
mod wallet;
|
||||
mod wallet_participation;
|
||||
|
||||
@@ -49,6 +51,7 @@ pub use liquidity_event::KbLiquidityEventEntity;
|
||||
pub use observed_token::KbObservedTokenEntity;
|
||||
pub use onchain_observation::KbOnchainObservationEntity;
|
||||
pub use pair::KbPairEntity;
|
||||
pub use pair_metric::KbPairMetricEntity;
|
||||
pub use pool::KbPoolEntity;
|
||||
pub use pool_listing::KbPoolListingEntity;
|
||||
pub use pool_origin::KbPoolOriginEntity;
|
||||
@@ -57,5 +60,6 @@ pub use swap::KbSwapEntity;
|
||||
pub use token::KbTokenEntity;
|
||||
pub use token_burn_event::KbTokenBurnEventEntity;
|
||||
pub use token_mint_event::KbTokenMintEventEntity;
|
||||
pub use trade_event::KbTradeEventEntity;
|
||||
pub use wallet::KbWalletEntity;
|
||||
pub use wallet_participation::KbWalletParticipationEntity;
|
||||
|
||||
36
kb_lib/src/db/entities/pair_metric.rs
Normal file
36
kb_lib/src/db/entities/pair_metric.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
// file: kb_lib/src/db/entities/pair_metric.rs
|
||||
|
||||
//! Pair-metric entity.
|
||||
|
||||
/// Persisted pair-metric row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbPairMetricEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Related pair id.
|
||||
pub pair_id: i64,
|
||||
/// Optional first observed slot.
|
||||
pub first_slot: std::option::Option<i64>,
|
||||
/// Optional last observed slot.
|
||||
pub last_slot: std::option::Option<i64>,
|
||||
/// Optional first observed signature.
|
||||
pub first_signature: std::option::Option<std::string::String>,
|
||||
/// Optional last observed signature.
|
||||
pub last_signature: std::option::Option<std::string::String>,
|
||||
/// Total trade count.
|
||||
pub trade_count: i64,
|
||||
/// Total buy count.
|
||||
pub buy_count: i64,
|
||||
/// Total sell count.
|
||||
pub sell_count: i64,
|
||||
/// Optional cumulative raw base volume.
|
||||
pub cumulative_base_amount_raw: std::option::Option<std::string::String>,
|
||||
/// Optional cumulative raw quote volume.
|
||||
pub cumulative_quote_amount_raw: std::option::Option<std::string::String>,
|
||||
/// Optional last derived quote-per-base price.
|
||||
pub last_price_quote_per_base: std::option::Option<f64>,
|
||||
/// Creation timestamp encoded as RFC3339 UTC text.
|
||||
pub created_at: std::string::String,
|
||||
/// Update timestamp encoded as RFC3339 UTC text.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
46
kb_lib/src/db/entities/trade_event.rs
Normal file
46
kb_lib/src/db/entities/trade_event.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
// file: kb_lib/src/db/entities/trade_event.rs
|
||||
|
||||
//! Trade-event entity.
|
||||
|
||||
/// Persisted trade-event row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbTradeEventEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Related DEX id.
|
||||
pub dex_id: i64,
|
||||
/// Related pool id.
|
||||
pub pool_id: i64,
|
||||
/// Related pair id.
|
||||
pub pair_id: i64,
|
||||
/// Related transaction id.
|
||||
pub transaction_id: i64,
|
||||
/// Related decoded event id.
|
||||
pub decoded_event_id: i64,
|
||||
/// Related transaction signature.
|
||||
pub signature: std::string::String,
|
||||
/// Optional observed slot.
|
||||
pub slot: std::option::Option<i64>,
|
||||
/// Stable trade side.
|
||||
pub trade_side: std::string::String,
|
||||
/// Related base token id.
|
||||
pub base_token_id: i64,
|
||||
/// Related quote token id.
|
||||
pub quote_token_id: i64,
|
||||
/// Optional raw base amount.
|
||||
pub base_amount_raw: std::option::Option<std::string::String>,
|
||||
/// Optional raw quote amount.
|
||||
pub quote_amount_raw: std::option::Option<std::string::String>,
|
||||
/// Optional derived quote-per-base price.
|
||||
pub price_quote_per_base: std::option::Option<f64>,
|
||||
/// Observation source kind.
|
||||
pub source_kind: i16,
|
||||
/// Optional logical source endpoint name.
|
||||
pub source_endpoint_name: std::option::Option<std::string::String>,
|
||||
/// Persisted payload JSON.
|
||||
pub payload_json: std::string::String,
|
||||
/// Creation timestamp encoded as RFC3339 UTC text.
|
||||
pub created_at: std::string::String,
|
||||
/// Update timestamp encoded as RFC3339 UTC text.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
@@ -23,6 +23,7 @@ mod liquidity_event;
|
||||
mod observed_token;
|
||||
mod onchain_observation;
|
||||
mod pair;
|
||||
mod pair_metric;
|
||||
mod pool;
|
||||
mod pool_listing;
|
||||
mod pool_origin;
|
||||
@@ -31,6 +32,7 @@ mod swap;
|
||||
mod token;
|
||||
mod token_burn_event;
|
||||
mod token_mint_event;
|
||||
mod trade_event;
|
||||
mod wallet;
|
||||
mod wallet_participation;
|
||||
|
||||
@@ -81,6 +83,9 @@ pub use onchain_observation::list_recent_onchain_observations;
|
||||
pub use pair::get_pair_by_pool_id;
|
||||
pub use pair::list_pairs;
|
||||
pub use pair::upsert_pair;
|
||||
pub use pair_metric::get_pair_metric_by_pair_id;
|
||||
pub use pair_metric::list_pair_metrics;
|
||||
pub use pair_metric::upsert_pair_metric;
|
||||
pub use pool::get_pool_by_address;
|
||||
pub use pool::list_pools;
|
||||
pub use pool::upsert_pool;
|
||||
@@ -100,6 +105,9 @@ pub use token_burn_event::list_recent_token_burn_events;
|
||||
pub use token_burn_event::upsert_token_burn_event;
|
||||
pub use token_mint_event::list_recent_token_mint_events;
|
||||
pub use token_mint_event::upsert_token_mint_event;
|
||||
pub use trade_event::get_trade_event_by_decoded_event_id;
|
||||
pub use trade_event::list_trade_events_by_pair_id;
|
||||
pub use trade_event::upsert_trade_event;
|
||||
pub use wallet::get_wallet_by_address;
|
||||
pub use wallet::list_wallets;
|
||||
pub use wallet::upsert_wallet;
|
||||
|
||||
186
kb_lib/src/db/queries/pair_metric.rs
Normal file
186
kb_lib/src/db/queries/pair_metric.rs
Normal file
@@ -0,0 +1,186 @@
|
||||
// file: kb_lib/src/db/queries/pair_metric.rs
|
||||
|
||||
//! Queries for `kb_pair_metrics`.
|
||||
|
||||
/// Inserts or updates one pair-metric row and returns its stable internal id.
|
||||
pub async fn upsert_pair_metric(
|
||||
database: &crate::KbDatabase,
|
||||
dto: &crate::KbPairMetricDto,
|
||||
) -> Result<i64, crate::KbError> {
|
||||
match database.connection() {
|
||||
crate::KbDatabaseConnection::Sqlite(pool) => {
|
||||
let query_result = sqlx::query(
|
||||
r#"
|
||||
INSERT INTO kb_pair_metrics (
|
||||
pair_id,
|
||||
first_slot,
|
||||
last_slot,
|
||||
first_signature,
|
||||
last_signature,
|
||||
trade_count,
|
||||
buy_count,
|
||||
sell_count,
|
||||
cumulative_base_amount_raw,
|
||||
cumulative_quote_amount_raw,
|
||||
last_price_quote_per_base,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(pair_id) DO UPDATE SET
|
||||
first_slot = excluded.first_slot,
|
||||
last_slot = excluded.last_slot,
|
||||
first_signature = excluded.first_signature,
|
||||
last_signature = excluded.last_signature,
|
||||
trade_count = excluded.trade_count,
|
||||
buy_count = excluded.buy_count,
|
||||
sell_count = excluded.sell_count,
|
||||
cumulative_base_amount_raw = excluded.cumulative_base_amount_raw,
|
||||
cumulative_quote_amount_raw = excluded.cumulative_quote_amount_raw,
|
||||
last_price_quote_per_base = excluded.last_price_quote_per_base,
|
||||
updated_at = excluded.updated_at
|
||||
"#,
|
||||
)
|
||||
.bind(dto.pair_id)
|
||||
.bind(dto.first_slot)
|
||||
.bind(dto.last_slot)
|
||||
.bind(dto.first_signature.clone())
|
||||
.bind(dto.last_signature.clone())
|
||||
.bind(dto.trade_count)
|
||||
.bind(dto.buy_count)
|
||||
.bind(dto.sell_count)
|
||||
.bind(dto.cumulative_base_amount_raw.clone())
|
||||
.bind(dto.cumulative_quote_amount_raw.clone())
|
||||
.bind(dto.last_price_quote_per_base)
|
||||
.bind(dto.created_at.to_rfc3339())
|
||||
.bind(dto.updated_at.to_rfc3339())
|
||||
.execute(pool)
|
||||
.await;
|
||||
if let Err(error) = query_result {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot upsert kb_pair_metrics on sqlite: {}",
|
||||
error
|
||||
)));
|
||||
}
|
||||
let id_result = sqlx::query_scalar::<sqlx::Sqlite, i64>(
|
||||
r#"
|
||||
SELECT id
|
||||
FROM kb_pair_metrics
|
||||
WHERE pair_id = ?
|
||||
LIMIT 1
|
||||
"#,
|
||||
)
|
||||
.bind(dto.pair_id)
|
||||
.fetch_one(pool)
|
||||
.await;
|
||||
match id_result {
|
||||
Ok(id) => Ok(id),
|
||||
Err(error) => Err(crate::KbError::Db(format!(
|
||||
"cannot fetch kb_pair_metrics id for pair_id '{}' on sqlite: {}",
|
||||
dto.pair_id, error
|
||||
))),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns one pair-metric row identified by its pair id, if it exists.
|
||||
pub async fn get_pair_metric_by_pair_id(
|
||||
database: &crate::KbDatabase,
|
||||
pair_id: i64,
|
||||
) -> Result<std::option::Option<crate::KbPairMetricDto>, crate::KbError> {
|
||||
match database.connection() {
|
||||
crate::KbDatabaseConnection::Sqlite(pool) => {
|
||||
let query_result = sqlx::query_as::<sqlx::Sqlite, crate::KbPairMetricEntity>(
|
||||
r#"
|
||||
SELECT
|
||||
id,
|
||||
pair_id,
|
||||
first_slot,
|
||||
last_slot,
|
||||
first_signature,
|
||||
last_signature,
|
||||
trade_count,
|
||||
buy_count,
|
||||
sell_count,
|
||||
cumulative_base_amount_raw,
|
||||
cumulative_quote_amount_raw,
|
||||
last_price_quote_per_base,
|
||||
created_at,
|
||||
updated_at
|
||||
FROM kb_pair_metrics
|
||||
WHERE pair_id = ?
|
||||
LIMIT 1
|
||||
"#,
|
||||
)
|
||||
.bind(pair_id)
|
||||
.fetch_optional(pool)
|
||||
.await;
|
||||
let entity_option = match query_result {
|
||||
Ok(entity_option) => entity_option,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot read kb_pair_metrics by pair_id '{}' on sqlite: {}",
|
||||
pair_id, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
match entity_option {
|
||||
Some(entity) => crate::KbPairMetricDto::try_from(entity).map(Some),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lists all pair-metric rows ordered by pair id.
|
||||
pub async fn list_pair_metrics(
|
||||
database: &crate::KbDatabase,
|
||||
) -> Result<std::vec::Vec<crate::KbPairMetricDto>, crate::KbError> {
|
||||
match database.connection() {
|
||||
crate::KbDatabaseConnection::Sqlite(pool) => {
|
||||
let query_result = sqlx::query_as::<sqlx::Sqlite, crate::KbPairMetricEntity>(
|
||||
r#"
|
||||
SELECT
|
||||
id,
|
||||
pair_id,
|
||||
first_slot,
|
||||
last_slot,
|
||||
first_signature,
|
||||
last_signature,
|
||||
trade_count,
|
||||
buy_count,
|
||||
sell_count,
|
||||
cumulative_base_amount_raw,
|
||||
cumulative_quote_amount_raw,
|
||||
last_price_quote_per_base,
|
||||
created_at,
|
||||
updated_at
|
||||
FROM kb_pair_metrics
|
||||
ORDER BY pair_id ASC
|
||||
"#,
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await;
|
||||
let entities = match query_result {
|
||||
Ok(entities) => entities,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot list kb_pair_metrics on sqlite: {}",
|
||||
error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let mut dtos = std::vec::Vec::new();
|
||||
for entity in entities {
|
||||
let dto_result = crate::KbPairMetricDto::try_from(entity);
|
||||
let dto = match dto_result {
|
||||
Ok(dto) => dto,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
dtos.push(dto);
|
||||
}
|
||||
Ok(dtos)
|
||||
}
|
||||
}
|
||||
}
|
||||
208
kb_lib/src/db/queries/trade_event.rs
Normal file
208
kb_lib/src/db/queries/trade_event.rs
Normal file
@@ -0,0 +1,208 @@
|
||||
// file: kb_lib/src/db/queries/trade_event.rs
|
||||
|
||||
//! Queries for `kb_trade_events`.
|
||||
|
||||
/// Inserts or updates one trade-event row and returns its stable internal id.
|
||||
pub async fn upsert_trade_event(
|
||||
database: &crate::KbDatabase,
|
||||
dto: &crate::KbTradeEventDto,
|
||||
) -> Result<i64, crate::KbError> {
|
||||
match database.connection() {
|
||||
crate::KbDatabaseConnection::Sqlite(pool) => {
|
||||
let query_result = sqlx::query(
|
||||
r#"
|
||||
INSERT INTO kb_trade_events (
|
||||
dex_id,
|
||||
pool_id,
|
||||
pair_id,
|
||||
transaction_id,
|
||||
decoded_event_id,
|
||||
signature,
|
||||
slot,
|
||||
trade_side,
|
||||
base_token_id,
|
||||
quote_token_id,
|
||||
base_amount_raw,
|
||||
quote_amount_raw,
|
||||
price_quote_per_base,
|
||||
source_kind,
|
||||
source_endpoint_name,
|
||||
payload_json,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(decoded_event_id) DO UPDATE SET
|
||||
updated_at = excluded.updated_at
|
||||
"#,
|
||||
)
|
||||
.bind(dto.dex_id)
|
||||
.bind(dto.pool_id)
|
||||
.bind(dto.pair_id)
|
||||
.bind(dto.transaction_id)
|
||||
.bind(dto.decoded_event_id)
|
||||
.bind(dto.signature.clone())
|
||||
.bind(dto.slot)
|
||||
.bind(kb_trade_side_to_string(dto.trade_side))
|
||||
.bind(dto.base_token_id)
|
||||
.bind(dto.quote_token_id)
|
||||
.bind(dto.base_amount_raw.clone())
|
||||
.bind(dto.quote_amount_raw.clone())
|
||||
.bind(dto.price_quote_per_base)
|
||||
.bind(dto.source_kind.to_i16())
|
||||
.bind(dto.source_endpoint_name.clone())
|
||||
.bind(dto.payload_json.clone())
|
||||
.bind(dto.created_at.to_rfc3339())
|
||||
.bind(dto.updated_at.to_rfc3339())
|
||||
.execute(pool)
|
||||
.await;
|
||||
if let Err(error) = query_result {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot upsert kb_trade_events on sqlite: {}",
|
||||
error
|
||||
)));
|
||||
}
|
||||
|
||||
let id_result = sqlx::query_scalar::<sqlx::Sqlite, i64>(
|
||||
r#"
|
||||
SELECT id
|
||||
FROM kb_trade_events
|
||||
WHERE decoded_event_id = ?
|
||||
LIMIT 1
|
||||
"#,
|
||||
)
|
||||
.bind(dto.decoded_event_id)
|
||||
.fetch_one(pool)
|
||||
.await;
|
||||
match id_result {
|
||||
Ok(id) => Ok(id),
|
||||
Err(error) => Err(crate::KbError::Db(format!(
|
||||
"cannot fetch kb_trade_events id for decoded_event_id '{}' on sqlite: {}",
|
||||
dto.decoded_event_id, error
|
||||
))),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns one trade-event row identified by its decoded-event id, if it exists.
|
||||
pub async fn get_trade_event_by_decoded_event_id(
|
||||
database: &crate::KbDatabase,
|
||||
decoded_event_id: i64,
|
||||
) -> Result<std::option::Option<crate::KbTradeEventDto>, crate::KbError> {
|
||||
match database.connection() {
|
||||
crate::KbDatabaseConnection::Sqlite(pool) => {
|
||||
let query_result = sqlx::query_as::<sqlx::Sqlite, crate::KbTradeEventEntity>(
|
||||
r#"
|
||||
SELECT
|
||||
id,
|
||||
dex_id,
|
||||
pool_id,
|
||||
pair_id,
|
||||
transaction_id,
|
||||
decoded_event_id,
|
||||
signature,
|
||||
slot,
|
||||
trade_side,
|
||||
base_token_id,
|
||||
quote_token_id,
|
||||
base_amount_raw,
|
||||
quote_amount_raw,
|
||||
price_quote_per_base,
|
||||
source_kind,
|
||||
source_endpoint_name,
|
||||
payload_json,
|
||||
created_at,
|
||||
updated_at
|
||||
FROM kb_trade_events
|
||||
WHERE decoded_event_id = ?
|
||||
LIMIT 1
|
||||
"#,
|
||||
)
|
||||
.bind(decoded_event_id)
|
||||
.fetch_optional(pool)
|
||||
.await;
|
||||
let entity_option = match query_result {
|
||||
Ok(entity_option) => entity_option,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot read kb_trade_events by decoded_event_id '{}' on sqlite: {}",
|
||||
decoded_event_id, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
match entity_option {
|
||||
Some(entity) => crate::KbTradeEventDto::try_from(entity).map(Some),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lists trade-event rows for one pair id ordered by creation time then id.
|
||||
pub async fn list_trade_events_by_pair_id(
|
||||
database: &crate::KbDatabase,
|
||||
pair_id: i64,
|
||||
) -> Result<std::vec::Vec<crate::KbTradeEventDto>, crate::KbError> {
|
||||
match database.connection() {
|
||||
crate::KbDatabaseConnection::Sqlite(pool) => {
|
||||
let query_result = sqlx::query_as::<sqlx::Sqlite, crate::KbTradeEventEntity>(
|
||||
r#"
|
||||
SELECT
|
||||
id,
|
||||
dex_id,
|
||||
pool_id,
|
||||
pair_id,
|
||||
transaction_id,
|
||||
decoded_event_id,
|
||||
signature,
|
||||
slot,
|
||||
trade_side,
|
||||
base_token_id,
|
||||
quote_token_id,
|
||||
base_amount_raw,
|
||||
quote_amount_raw,
|
||||
price_quote_per_base,
|
||||
source_kind,
|
||||
source_endpoint_name,
|
||||
payload_json,
|
||||
created_at,
|
||||
updated_at
|
||||
FROM kb_trade_events
|
||||
WHERE pair_id = ?
|
||||
ORDER BY created_at ASC, id ASC
|
||||
"#,
|
||||
)
|
||||
.bind(pair_id)
|
||||
.fetch_all(pool)
|
||||
.await;
|
||||
let entities = match query_result {
|
||||
Ok(entities) => entities,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot list kb_trade_events by pair_id '{}' on sqlite: {}",
|
||||
pair_id, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let mut dtos = std::vec::Vec::new();
|
||||
for entity in entities {
|
||||
let dto_result = crate::KbTradeEventDto::try_from(entity);
|
||||
let dto = match dto_result {
|
||||
Ok(dto) => dto,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
dtos.push(dto);
|
||||
}
|
||||
Ok(dtos)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn kb_trade_side_to_string(value: crate::KbSwapTradeSide) -> &'static str {
|
||||
match value {
|
||||
crate::KbSwapTradeSide::BuyBase => "BuyBase",
|
||||
crate::KbSwapTradeSide::SellBase => "SellBase",
|
||||
crate::KbSwapTradeSide::Unknown => "Unknown",
|
||||
}
|
||||
}
|
||||
@@ -294,6 +294,22 @@ pub(crate) async fn ensure_schema(database: &crate::KbDatabase) -> Result<(), cr
|
||||
if let Err(error) = result {
|
||||
return Err(error);
|
||||
}
|
||||
let result = create_kb_trade_events_table(pool).await;
|
||||
if let Err(error) = result {
|
||||
return Err(error);
|
||||
}
|
||||
let result = create_kb_idx_trade_events_pair_id(pool).await;
|
||||
if let Err(error) = result {
|
||||
return Err(error);
|
||||
}
|
||||
let result = create_kb_idx_trade_events_pool_id(pool).await;
|
||||
if let Err(error) = result {
|
||||
return Err(error);
|
||||
}
|
||||
let result = create_kb_pair_metrics_table(pool).await;
|
||||
if let Err(error) = result {
|
||||
return Err(error);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1608,3 +1624,92 @@ ON kb_wallet_participations(transaction_id)
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn create_kb_trade_events_table(pool: &sqlx::SqlitePool) -> Result<(), crate::KbError> {
|
||||
execute_sqlite_schema_statement(
|
||||
pool,
|
||||
"create_kb_trade_events_table",
|
||||
r#"
|
||||
CREATE TABLE IF NOT EXISTS kb_trade_events (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
dex_id INTEGER NOT NULL,
|
||||
pool_id INTEGER NOT NULL,
|
||||
pair_id INTEGER NOT NULL,
|
||||
transaction_id INTEGER NOT NULL,
|
||||
decoded_event_id INTEGER NOT NULL UNIQUE,
|
||||
signature TEXT NOT NULL,
|
||||
slot INTEGER NULL,
|
||||
trade_side TEXT NOT NULL,
|
||||
base_token_id INTEGER NOT NULL,
|
||||
quote_token_id INTEGER NOT NULL,
|
||||
base_amount_raw TEXT NULL,
|
||||
quote_amount_raw TEXT NULL,
|
||||
price_quote_per_base REAL NULL,
|
||||
source_kind INTEGER NOT NULL,
|
||||
source_endpoint_name TEXT NULL,
|
||||
payload_json TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
FOREIGN KEY(dex_id) REFERENCES kb_dexes(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(pool_id) REFERENCES kb_pools(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(pair_id) REFERENCES kb_pairs(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(transaction_id) REFERENCES kb_chain_transactions(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(decoded_event_id) REFERENCES kb_dex_decoded_events(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(base_token_id) REFERENCES kb_tokens(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(quote_token_id) REFERENCES kb_tokens(id) ON DELETE CASCADE
|
||||
)
|
||||
"#,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn create_kb_idx_trade_events_pair_id(pool: &sqlx::SqlitePool) -> Result<(), crate::KbError> {
|
||||
execute_sqlite_schema_statement(
|
||||
pool,
|
||||
"create_kb_idx_trade_events_pair_id",
|
||||
r#"
|
||||
CREATE INDEX IF NOT EXISTS kb_idx_trade_events_pair_id
|
||||
ON kb_trade_events(pair_id)
|
||||
"#,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn create_kb_idx_trade_events_pool_id(pool: &sqlx::SqlitePool) -> Result<(), crate::KbError> {
|
||||
execute_sqlite_schema_statement(
|
||||
pool,
|
||||
"create_kb_idx_trade_events_pool_id",
|
||||
r#"
|
||||
CREATE INDEX IF NOT EXISTS kb_idx_trade_events_pool_id
|
||||
ON kb_trade_events(pool_id)
|
||||
"#,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn create_kb_pair_metrics_table(pool: &sqlx::SqlitePool) -> Result<(), crate::KbError> {
|
||||
execute_sqlite_schema_statement(
|
||||
pool,
|
||||
"create_kb_pair_metrics_table",
|
||||
r#"
|
||||
CREATE TABLE IF NOT EXISTS kb_pair_metrics (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
pair_id INTEGER NOT NULL UNIQUE,
|
||||
first_slot INTEGER NULL,
|
||||
last_slot INTEGER NULL,
|
||||
first_signature TEXT NULL,
|
||||
last_signature TEXT NULL,
|
||||
trade_count INTEGER NOT NULL,
|
||||
buy_count INTEGER NOT NULL,
|
||||
sell_count INTEGER NOT NULL,
|
||||
cumulative_base_amount_raw TEXT NULL,
|
||||
cumulative_quote_amount_raw TEXT NULL,
|
||||
last_price_quote_per_base REAL NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
FOREIGN KEY(pair_id) REFERENCES kb_pairs(id) ON DELETE CASCADE
|
||||
)
|
||||
"#,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user