From 99f428fa603afca8f21596b1abadc79295c8b683 Mon Sep 17 00:00:00 2001 From: Miguel Palhas Date: Mon, 2 Sep 2024 16:44:09 +0100 Subject: [PATCH] History endpoint: return the tx history for the authenticated address (#33) --- src/api/app.rs | 12 ++++++++++++ src/db/mod.rs | 15 +++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/src/api/app.rs b/src/api/app.rs index e4818ce..25c74ad 100644 --- a/src/api/app.rs +++ b/src/api/app.rs @@ -29,6 +29,7 @@ pub fn app(jwt_secret: String, state: AppState) -> Router { let protected_routes = Router::new() .route("/test", post(test)) + .route("/history", post(history)) .route_layer(from_extractor::()); let public_routes = Router::new() @@ -69,6 +70,17 @@ pub async fn test(State(_state): State) -> impl IntoResponse { Json(json!({"foo": "bar"})) } +pub async fn history( + State(state): State, + Claims { sub: address, .. }: Claims, +) -> ApiResult { + let addr = alloy_primitives::Address::from_str(&format!("0x{:x}", address)).unwrap(); + + let history = state.db.history(&addr.into()).await?; + + Ok(Json(json!(history))) +} + #[derive(Debug, Serialize, Deserialize)] pub struct IsWhitelistedResponse { address: Address, diff --git a/src/db/mod.rs b/src/db/mod.rs index d93ece8..379c531 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -10,6 +10,7 @@ use diesel_async::{ AsyncConnection, AsyncPgConnection, RunQueryDsl, }; use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness}; +use models::Txs; use tokio::sync::mpsc::UnboundedSender; use tracing::instrument; @@ -197,6 +198,20 @@ impl Db { Ok(res > 0) } + pub async fn history(&self, address: &Address) -> Result> { + use schema::txs::{self, dsl}; + let mut conn = self.pool.get().await?; + + Ok(schema::txs::table + .filter(dsl::chain_id.eq(self.chain_id)) + .filter(dsl::address.eq(address)) + .select((txs::address, txs::hash)) + .select(Txs::as_select()) + .order(dsl::block_number.asc()) + .load(&mut conn) + .await?) + } + pub async fn get_addresses(&self) -> Result> { use schema::accounts::dsl; let mut conn = self.pool.get().await?;