use futures::stream::{BoxStream, StreamExt, TryStreamExt};
use moonproof_macros::async_trait;
use subxt::config::substrate::H256;
use subxt::{OnlineClient, SubstrateConfig};
use crate::client::{Genesis, NodeClient, SerializedTransaction};
use crate::config::Config;
use crate::error::NodeClientError;
use crate::event::SubmissionEvent;
use crate::status::{SubmissionOutcome, TxStatus};
const MIDNIGHT_PALLET: &str = "Midnight";
const SEND_MN_TRANSACTION: &str = "send_mn_transaction";
pub struct PolkadotNodeClient {
config: Config,
api: OnlineClient<SubstrateConfig>,
}
impl PolkadotNodeClient {
pub async fn connect(config: Config) -> Result<Self, NodeClientError> {
let url = config.node_url.to_string();
let api = OnlineClient::<SubstrateConfig>::from_insecure_url(&url)
.await
.map_err(|e| NodeClientError::Connection {
message: format!("failed to connect to {url}: {e}"),
source: Some(Box::new(e)),
})?;
Ok(Self { config, api })
}
#[must_use]
pub fn api(&self) -> &OnlineClient<SubstrateConfig> {
&self.api
}
#[must_use]
pub fn config(&self) -> &Config {
&self.config
}
}
fn format_hash(hash: H256) -> String {
format!("0x{}", hex::encode(hash.as_bytes()))
}
async fn resolve_block_height(
api: &OnlineClient<SubstrateConfig>,
block_hash: H256,
) -> Result<u64, NodeClientError> {
let at_block = api
.at_block(block_hash)
.await
.map_err(|e| NodeClientError::Parse {
message: format!(
"failed to fetch header for block {}: {e}",
format_hash(block_hash)
),
source: Some(Box::new(e)),
})?;
Ok(at_block.block_number())
}
async fn translate_status(
status: subxt::tx::TransactionStatus<
SubstrateConfig,
subxt::client::OnlineClientAtBlockImpl<SubstrateConfig>,
>,
api: &OnlineClient<SubstrateConfig>,
tx: &[u8],
tx_hash: &str,
) -> Result<SubmissionOutcome, NodeClientError> {
use subxt::tx::TransactionStatus as S;
let outcome = match status {
S::Validated | S::Broadcasted | S::NoLongerInBestBlock => {
SubmissionOutcome::from_status(TxStatus::Ready, tx, tx_hash)
}
S::InBestBlock(info) => {
let block_hash = info.block_hash();
let block_height = resolve_block_height(api, block_hash).await?;
SubmissionOutcome::from_status(
TxStatus::InBlock {
block_hash: format_hash(block_hash),
block_height,
},
tx,
tx_hash,
)
}
S::InFinalizedBlock(info) => {
let block_hash = info.block_hash();
let block_height = resolve_block_height(api, block_hash).await?;
SubmissionOutcome::from_status(
TxStatus::Finalized {
block_hash: format_hash(block_hash),
block_height,
},
tx,
tx_hash,
)
}
S::Error { message } => SubmissionOutcome::Fail(NodeClientError::Submission {
message: format!("node reported transaction error: {message}"),
tx_data: tx.to_vec(),
source: None,
}),
S::Invalid { message } => SubmissionOutcome::Fail(NodeClientError::TransactionInvalid {
tx_data: tx.to_vec(),
source: Some(message.into()),
}),
S::Dropped { message: _ } => SubmissionOutcome::Fail(NodeClientError::TransactionDropped {
tx_data: tx.to_vec(),
}),
};
Ok(outcome)
}
#[async_trait]
impl NodeClient for PolkadotNodeClient {
fn genesis_hash_hex(&self) -> Option<String> {
Some(format_hash(self.api.genesis_hash()))
}
async fn send_midnight_transaction(
&self,
tx: SerializedTransaction,
) -> Result<BoxStream<'static, Result<SubmissionEvent, NodeClientError>>, NodeClientError> {
let payload = subxt::dynamic::tx(
MIDNIGHT_PALLET,
SEND_MN_TRANSACTION,
vec![subxt::dynamic::Value::from_bytes(tx.clone())],
);
let txs = self
.api
.tx()
.await
.map_err(|e| NodeClientError::Connection {
message: format!("failed to fetch transactions client: {e}"),
source: Some(Box::new(e)),
})?;
let submittable = txs.create_unsigned(&payload).map_err(|e| {
NodeClientError::Submission {
message: format!(
"failed to build unsigned extrinsic for {MIDNIGHT_PALLET}.{SEND_MN_TRANSACTION}: {e}"
),
tx_data: tx.clone(),
source: Some(Box::new(e)),
}
})?;
let progress =
submittable
.submit_and_watch()
.await
.map_err(|e| NodeClientError::Submission {
message: format!("submit_and_watch rejected the extrinsic: {e}"),
tx_data: tx.clone(),
source: Some(Box::new(e)),
})?;
let tx_hash = format_hash(progress.extrinsic_hash());
let api = self.api.clone();
let tx_for_err = tx.clone();
let tx_for_ok = tx;
let mapped = progress
.map_err(move |e| NodeClientError::Submission {
message: format!("transaction progress error: {e}"),
tx_data: tx_for_err.clone(),
source: Some(Box::new(e)),
})
.and_then(move |status| {
let api = api.clone();
let tx_bytes = tx_for_ok.clone();
let tx_hash = tx_hash.clone();
async move {
let outcome = translate_status(status, &api, &tx_bytes, &tx_hash).await?;
match outcome {
SubmissionOutcome::Emit(ev) | SubmissionOutcome::EmitAndFinish(ev) => {
Ok(ev)
}
SubmissionOutcome::Fail(e) => Err(e),
}
}
});
Ok(mapped.boxed())
}
async fn get_genesis(&self) -> Result<Genesis, NodeClientError> {
let genesis_hash = self.api.genesis_hash();
let at_block =
self.api
.at_block(genesis_hash)
.await
.map_err(|e| NodeClientError::Connection {
message: format!(
"failed to load genesis block {}: {e}",
format_hash(genesis_hash)
),
source: Some(Box::new(e)),
})?;
let extrinsics =
at_block
.extrinsics()
.fetch()
.await
.map_err(|e| NodeClientError::Connection {
message: format!("failed to fetch genesis extrinsics: {e}"),
source: Some(Box::new(e)),
})?;
let mut transactions: Vec<SerializedTransaction> = Vec::new();
for item in extrinsics.iter() {
let ext = item.map_err(|e| NodeClientError::Parse {
message: format!("failed to decode genesis extrinsic: {e}"),
source: Some(Box::new(e)),
})?;
if ext.pallet_name() != MIDNIGHT_PALLET || ext.call_name() != SEND_MN_TRANSACTION {
tracing::debug!(
target: "moonproof::node-client",
"skipping genesis extrinsic #{}: {}.{}",
ext.index(),
ext.pallet_name(),
ext.call_name(),
);
continue;
}
let (tx_bytes,): (Vec<u8>,) = ext
.decode_call_data_fields_unchecked_as()
.map_err(|e| NodeClientError::Parse {
message: format!(
"failed to decode {MIDNIGHT_PALLET}.{SEND_MN_TRANSACTION} args as (Vec<u8>,): {e}"
),
source: Some(Box::new(e)),
})?;
transactions.push(tx_bytes);
}
Ok(Genesis { transactions })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn format_hash_renders_canonical_hex_with_prefix() {
let bytes = [0xabu8; 32];
let hash = H256::from(bytes);
let rendered = format_hash(hash);
assert!(rendered.starts_with("0x"));
assert_eq!(rendered.len(), 2 + 64);
assert!(rendered.chars().skip(2).all(|c| c.is_ascii_hexdigit()));
}
#[test]
fn midnight_pallet_constants_match_ts_dispatch_names() {
assert_eq!(MIDNIGHT_PALLET, "Midnight");
assert_eq!(SEND_MN_TRANSACTION, "send_mn_transaction");
}
}