use crate::{
Blockchain, TxPool,
rpc_server::{RpcServerError, types::HexString},
};
use jsonrpsee::{core::RpcResult, proc_macros::rpc};
use std::sync::Arc;
#[rpc(server, namespace = "dev")]
pub trait DevApi {
#[method(name = "newBlock")]
async fn new_block(&self) -> RpcResult<NewBlockResult>;
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NewBlockResult {
pub hash: String,
pub number: u32,
pub extrinsics_count: usize,
}
pub struct DevApi {
blockchain: Arc<Blockchain>,
txpool: Arc<TxPool>,
}
impl DevApi {
pub fn new(blockchain: Arc<Blockchain>, txpool: Arc<TxPool>) -> Self {
Self { blockchain, txpool }
}
}
#[async_trait::async_trait]
impl DevApiServer for DevApi {
async fn new_block(&self) -> RpcResult<NewBlockResult> {
let pending_txs = self.txpool.drain().map_err(|e| {
RpcServerError::Internal(format!("Failed to drain transaction pool: {e}"))
})?;
let result = self
.blockchain
.build_block(pending_txs)
.await
.map_err(|e| RpcServerError::Internal(format!("Failed to build block: {e}")))?;
Ok(NewBlockResult {
hash: HexString::from_bytes(result.block.hash.as_bytes()).into(),
number: result.block.number,
extrinsics_count: result.block.extrinsics.len(),
})
}
}