From 11bf920c9109c61b3aadf4947efceac61dea2b02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Roycourt?= <11146088+remiroyc@users.noreply.github.com> Date: Fri, 12 Apr 2024 14:43:44 +0200 Subject: [PATCH] fix(api): mongodb query to return the total count of bridged tokens (#181) * feat(api): Enhance MongoDB query for accurate total count of bridged tokens * fix(api): mongo aggregation * fix: remove log info * feat: normalize contract addr --- apps/indexer/src/handlers/requests.rs | 5 +++- apps/indexer/src/storage/mongo/event_store.rs | 24 +++++++++---------- 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/apps/indexer/src/handlers/requests.rs b/apps/indexer/src/handlers/requests.rs index 0eda43ba..2729561f 100644 --- a/apps/indexer/src/handlers/requests.rs +++ b/apps/indexer/src/handlers/requests.rs @@ -123,9 +123,12 @@ pub async fn contract_stats( Path(eth_contract_address): Path, state: State, ) -> Result, (StatusCode, String)> { + let contract_address = normalize_hex(ð_contract_address) + .expect("Contract address shall be an hexadecimal string"); + let total_tokens_bridged_on_starknet = state .store - .get_total_tokens_bridged_on_starknet(ð_contract_address) + .get_total_tokens_bridged_on_starknet(&contract_address) .await .unwrap_or(0); diff --git a/apps/indexer/src/storage/mongo/event_store.rs b/apps/indexer/src/storage/mongo/event_store.rs index c4b98d2e..79e8905f 100644 --- a/apps/indexer/src/storage/mongo/event_store.rs +++ b/apps/indexer/src/storage/mongo/event_store.rs @@ -1,7 +1,7 @@ use anyhow::Result; use async_trait::async_trait; use futures::TryStreamExt; -use mongodb::bson::doc; +use mongodb::{bson::doc, options::AggregateOptions}; use super::MongoStore; use crate::storage::{store::EventStore, Event}; @@ -34,31 +34,31 @@ impl EventStore for MongoStore { } }, doc! { - "$project": { - "number_of_tokens": { "$size": "$token_ids" } - } + "$unwind": "$token_ids" }, doc! { "$group": { "_id": null, - "total_token_ids": { "$sum": "$number_of_tokens" } + "total_tokens": { + "$sum": 1 + } } }, ]; let mut cursor = self .starknet_bridge_requests - .aggregate(pipeline, None) + .aggregate(pipeline, AggregateOptions::default()) .await?; - let mut total_count: u64 = 0; - if let Some(doc) = cursor.try_next().await? { - if let Ok(count) = doc.get_i64("total_token_ids") { - total_count = count as u64; - } + let mut total_tokens: u64 = 0; + while let Some(doc) = cursor.try_next().await? { + if let Ok(total) = doc.get_i32("total_tokens") { + total_tokens += total as u64; + }; } - Ok(total_count) + Ok(total_tokens) } ///