feat(rpc): implement nu_getBlock handler

This commit is contained in:
Mukan Erkin TÖRÜK 2026-04-24 11:04:00 +03:00
parent 70b326a24f
commit f9925eba79

View file

@ -4,7 +4,7 @@ use crate::{
server::AppState, server::AppState,
types::{JsonRpcRequest, JsonRpcResponse}, types::{JsonRpcRequest, JsonRpcResponse},
}; };
use nu_block::types::RawTransaction; use nu_block::types::{Block, RawTransaction};
use nu_state::account::AccountState; use nu_state::account::AccountState;
pub async fn dispatch(req: JsonRpcRequest, state: &AppState) -> JsonRpcResponse { pub async fn dispatch(req: JsonRpcRequest, state: &AppState) -> JsonRpcResponse {
@ -12,7 +12,7 @@ pub async fn dispatch(req: JsonRpcRequest, state: &AppState) -> JsonRpcResponse
"nu_chainInfo" => handle_chain_info(&req, state), "nu_chainInfo" => handle_chain_info(&req, state),
"nu_getAccount" => handle_get_account(&req, state).await, "nu_getAccount" => handle_get_account(&req, state).await,
"nu_sendRawTx" => handle_send_raw_tx(&req, state).await, "nu_sendRawTx" => handle_send_raw_tx(&req, state).await,
"nu_getBlock" => not_implemented(&req, "nu_getBlock"), "nu_getBlock" => handle_get_block(&req, state).await,
"nu_getTx" => not_implemented(&req, "nu_getTx"), "nu_getTx" => not_implemented(&req, "nu_getTx"),
"nu_getStory" => not_implemented(&req, "nu_getStory"), "nu_getStory" => not_implemented(&req, "nu_getStory"),
"nu_getNode" => not_implemented(&req, "nu_getNode"), "nu_getNode" => not_implemented(&req, "nu_getNode"),
@ -90,6 +90,21 @@ async fn handle_send_raw_tx(req: &JsonRpcRequest, state: &AppState) -> JsonRpcRe
} }
} }
async fn handle_get_block(req: &JsonRpcRequest, state: &AppState) -> JsonRpcResponse {
let height: u64 = match req.params.get(0).and_then(|v| v.as_u64()) {
Some(h) => h,
None => return JsonRpcResponse::err(req.id.clone(), -32602, "Missing or invalid height param".into()),
};
let key = format!("block:{height}");
let db = state.db.lock().await;
match db.get::<Block>(&key) {
Ok(Some(block)) => JsonRpcResponse::ok(req.id.clone(), serde_json::to_value(block).unwrap()),
Ok(None) => JsonRpcResponse::ok(req.id.clone(), serde_json::Value::Null),
Err(e) => JsonRpcResponse::err(req.id.clone(), -32000, e.to_string()),
}
}
fn not_implemented(req: &JsonRpcRequest, method: &str) -> JsonRpcResponse { fn not_implemented(req: &JsonRpcRequest, method: &str) -> JsonRpcResponse {
JsonRpcResponse::err(req.id.clone(), -32000, format!("{method} not implemented yet")) JsonRpcResponse::err(req.id.clone(), -32000, format!("{method} not implemented yet"))
} }