Skip to content

Commit

Permalink
Feat: get txs. (#249)
Browse files Browse the repository at this point in the history
  • Loading branch information
sircsq authored Apr 7, 2024
1 parent 8bed25f commit 7c16c9b
Show file tree
Hide file tree
Showing 3 changed files with 105 additions and 5 deletions.
3 changes: 2 additions & 1 deletion explorer/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
mod service;
use crate::service::api::Api;
use crate::service::v2::block::{get_block_by_hash, get_block_by_num, get_blocks};
use crate::service::v2::transaction::get_tx_by_hash;
use crate::service::v2::transaction::{get_tx_by_hash, get_txs};
use anyhow::Result;
use axum::http::Method;
use axum::routing::get;
Expand Down Expand Up @@ -50,6 +50,7 @@ async fn main() -> Result<()> {
.route("/api/v2/hash/block", get(get_block_by_hash))
.route("/api/v2/blocks", get(get_blocks))
.route("/api/v2/hash/tx", get(get_tx_by_hash))
.route("/api/v2/txs", get(get_txs))
.layer(cors)
.with_state(app_state);
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
Expand Down
7 changes: 6 additions & 1 deletion explorer/src/service/v2/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,10 @@ pub fn internal_error<E>(err: E) -> (StatusCode, String)
where
E: std::error::Error,
{
(StatusCode::INTERNAL_SERVER_ERROR, err.to_string())
let err_msg = err.to_string();
if err_msg.contains("now rows") {
return (StatusCode::NOT_FOUND, "not found".to_string());
}

(StatusCode::INTERNAL_SERVER_ERROR, err_msg)
}
100 changes: 97 additions & 3 deletions explorer/src/service/v2/transaction.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,108 @@
use crate::service::v2::error::internal_error;
use crate::service::v2::error::Result;
use crate::service::v2::error::{internal_error, Result};
use crate::service::v2::QueryResult;
use crate::AppState;
use axum::extract::{Query, State};
use axum::Json;
use module::schema::TransactionResponse;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sqlx::Row;
use std::ops::Add;
use std::sync::Arc;

#[derive(Serialize, Deserialize)]
pub struct GetTxsParams {
pub from: Option<String>,
pub to: Option<String>,
pub ty: Option<i32>,
pub page: Option<i32>,
pub page_size: Option<i32>,
}

pub async fn get_txs(
State(state): State<Arc<AppState>>,
Query(params): Query<GetTxsParams>,
) -> Result<Json<QueryResult<Vec<TransactionResponse>>>> {
let mut conn = state.pool.acquire().await.map_err(internal_error)?;
let page = params.page.unwrap_or(1);
let page_size = params.page_size.unwrap_or(10);

let mut sql_query = String::from("SELECT tx_hash,block_hash,ty,timestamp,height,code,log,origin,result,value FROM transaction ");
let mut sql_total = String::from("SELECT count(*) FROM transaction ");
let mut query_params: Vec<String> = vec![];
if let Some(from) = params.from {
query_params.push(format!("sender='{}' ", from))
}
if let Some(to) = params.to {
query_params.push(format!("(receiver @? '$.addrs[*] ? (@==\"{}\")') ", to));
}
if let Some(ty) = params.ty {
query_params.push(format!("ty={} ", ty));
}
if !query_params.is_empty() {
sql_query = sql_query
.add("WHERE ")
.add(query_params.join("AND ").as_str());
sql_total = sql_total
.add("WHERE ")
.add(query_params.join("AND ").as_str());
}

sql_query = sql_query.add(
format!(
"ORDER BY timestamp DESC LIMIT {} OFFSET {} ",
page_size,
(page - 1) * page_size
)
.as_str(),
);

let row = sqlx::query(&sql_total)
.fetch_one(&mut *conn)
.await
.map_err(internal_error)?;
let total: i64 = row.try_get("count").map_err(internal_error)?;

let rows = sqlx::query(&sql_query)
.fetch_all(&mut *conn)
.await
.map_err(internal_error)?;
let mut txs: Vec<TransactionResponse> = vec![];
for row in rows {
let tx_hash: String = row.try_get("tx_hash").map_err(internal_error)?;
let block_hash: String = row.try_get("block_hash").map_err(internal_error)?;
let ty: i32 = row.try_get("ty").map_err(internal_error)?;
let timestamp: i64 = row.try_get("timestamp").map_err(internal_error)?;
let height: i64 = row.try_get("height").map_err(internal_error)?;
let code: i64 = row.try_get("code").map_err(internal_error)?;
let log: String = row.try_get("log").map_err(internal_error)?;
let origin: String = row.try_get("origin").map_err(internal_error)?;
let result: Value = row.try_get("result").map_err(internal_error)?;
let value: Value = row.try_get("value").map_err(internal_error)?;

txs.push(TransactionResponse {
tx_hash,
evm_tx_hash: "".to_string(),
block_hash,
height,
timestamp,
ty,
code,
log,
origin,
result,
value,
});
}

Ok(Json(QueryResult {
total,
page,
page_size,
data: txs,
}))
}

#[derive(Serialize, Deserialize)]
pub struct GetTxByHashParams {
pub hash: String,
Expand All @@ -31,7 +125,7 @@ pub async fn get_tx_by_hash(

let tx_hash: String = row.try_get("tx_hash").map_err(internal_error)?;
let block_hash: String = row.try_get("block_hash").map_err(internal_error)?;
let ty: i32 = row.try_get("ty_sub").map_err(internal_error)?;
let ty: i32 = row.try_get("ty").map_err(internal_error)?;
let timestamp: i64 = row.try_get("timestamp").map_err(internal_error)?;
let height: i64 = row.try_get("height").map_err(internal_error)?;
let code: i64 = row.try_get("code").map_err(internal_error)?;
Expand Down

0 comments on commit 7c16c9b

Please sign in to comment.