1use futures::stream::{BoxStream, StreamExt, TryStreamExt};
26use moonproof_macros::async_trait;
27use subxt::config::substrate::H256;
28use subxt::{OnlineClient, SubstrateConfig};
29
30use crate::client::{Genesis, NodeClient, SerializedTransaction};
31use crate::config::Config;
32use crate::error::NodeClientError;
33use crate::event::SubmissionEvent;
34use crate::status::{SubmissionOutcome, TxStatus};
35
36const MIDNIGHT_PALLET: &str = "Midnight";
39
40const SEND_MN_TRANSACTION: &str = "send_mn_transaction";
45
46pub struct PolkadotNodeClient {
53 config: Config,
54 api: OnlineClient<SubstrateConfig>,
55}
56
57impl PolkadotNodeClient {
58 pub async fn connect(config: Config) -> Result<Self, NodeClientError> {
63 let url = config.node_url.to_string();
64 let api = OnlineClient::<SubstrateConfig>::from_insecure_url(&url)
65 .await
66 .map_err(|e| NodeClientError::Connection {
67 message: format!("failed to connect to {url}: {e}"),
68 source: Some(Box::new(e)),
69 })?;
70 Ok(Self { config, api })
71 }
72
73 #[must_use]
76 pub fn api(&self) -> &OnlineClient<SubstrateConfig> {
77 &self.api
78 }
79
80 #[must_use]
82 pub fn config(&self) -> &Config {
83 &self.config
84 }
85}
86
87fn format_hash(hash: H256) -> String {
88 format!("0x{}", hex::encode(hash.as_bytes()))
89}
90
91async fn resolve_block_height(
92 api: &OnlineClient<SubstrateConfig>,
93 block_hash: H256,
94) -> Result<u64, NodeClientError> {
95 let at_block = api
96 .at_block(block_hash)
97 .await
98 .map_err(|e| NodeClientError::Parse {
99 message: format!(
100 "failed to fetch header for block {}: {e}",
101 format_hash(block_hash)
102 ),
103 source: Some(Box::new(e)),
104 })?;
105 Ok(at_block.block_number())
106}
107
108async fn translate_status(
112 status: subxt::tx::TransactionStatus<
113 SubstrateConfig,
114 subxt::client::OnlineClientAtBlockImpl<SubstrateConfig>,
115 >,
116 api: &OnlineClient<SubstrateConfig>,
117 tx: &[u8],
118 tx_hash: &str,
119) -> Result<SubmissionOutcome, NodeClientError> {
120 use subxt::tx::TransactionStatus as S;
121 let outcome = match status {
122 S::Validated | S::Broadcasted | S::NoLongerInBestBlock => {
126 SubmissionOutcome::from_status(TxStatus::Ready, tx, tx_hash)
127 }
128 S::InBestBlock(info) => {
129 let block_hash = info.block_hash();
130 let block_height = resolve_block_height(api, block_hash).await?;
131 SubmissionOutcome::from_status(
132 TxStatus::InBlock {
133 block_hash: format_hash(block_hash),
134 block_height,
135 },
136 tx,
137 tx_hash,
138 )
139 }
140 S::InFinalizedBlock(info) => {
141 let block_hash = info.block_hash();
142 let block_height = resolve_block_height(api, block_hash).await?;
143 SubmissionOutcome::from_status(
144 TxStatus::Finalized {
145 block_hash: format_hash(block_hash),
146 block_height,
147 },
148 tx,
149 tx_hash,
150 )
151 }
152 S::Error { message } => SubmissionOutcome::Fail(NodeClientError::Submission {
153 message: format!("node reported transaction error: {message}"),
154 tx_data: tx.to_vec(),
155 source: None,
156 }),
157 S::Invalid { message } => SubmissionOutcome::Fail(NodeClientError::TransactionInvalid {
158 tx_data: tx.to_vec(),
159 source: Some(message.into()),
160 }),
161 S::Dropped { message: _ } => SubmissionOutcome::Fail(NodeClientError::TransactionDropped {
165 tx_data: tx.to_vec(),
166 }),
167 };
168 Ok(outcome)
169}
170
171#[async_trait]
172impl NodeClient for PolkadotNodeClient {
173 fn genesis_hash_hex(&self) -> Option<String> {
174 Some(format_hash(self.api.genesis_hash()))
175 }
176
177 async fn send_midnight_transaction(
178 &self,
179 tx: SerializedTransaction,
180 ) -> Result<BoxStream<'static, Result<SubmissionEvent, NodeClientError>>, NodeClientError> {
181 let payload = subxt::dynamic::tx(
186 MIDNIGHT_PALLET,
187 SEND_MN_TRANSACTION,
188 vec![subxt::dynamic::Value::from_bytes(tx.clone())],
189 );
190
191 let txs = self
192 .api
193 .tx()
194 .await
195 .map_err(|e| NodeClientError::Connection {
196 message: format!("failed to fetch transactions client: {e}"),
197 source: Some(Box::new(e)),
198 })?;
199
200 let submittable = txs.create_unsigned(&payload).map_err(|e| {
201 NodeClientError::Submission {
202 message: format!(
203 "failed to build unsigned extrinsic for {MIDNIGHT_PALLET}.{SEND_MN_TRANSACTION}: {e}"
204 ),
205 tx_data: tx.clone(),
206 source: Some(Box::new(e)),
207 }
208 })?;
209
210 let progress =
211 submittable
212 .submit_and_watch()
213 .await
214 .map_err(|e| NodeClientError::Submission {
215 message: format!("submit_and_watch rejected the extrinsic: {e}"),
216 tx_data: tx.clone(),
217 source: Some(Box::new(e)),
218 })?;
219
220 let tx_hash = format_hash(progress.extrinsic_hash());
221 let api = self.api.clone();
222 let tx_for_err = tx.clone();
227 let tx_for_ok = tx;
228
229 let mapped = progress
234 .map_err(move |e| NodeClientError::Submission {
235 message: format!("transaction progress error: {e}"),
236 tx_data: tx_for_err.clone(),
237 source: Some(Box::new(e)),
238 })
239 .and_then(move |status| {
240 let api = api.clone();
241 let tx_bytes = tx_for_ok.clone();
242 let tx_hash = tx_hash.clone();
243 async move {
244 let outcome = translate_status(status, &api, &tx_bytes, &tx_hash).await?;
245 match outcome {
246 SubmissionOutcome::Emit(ev) | SubmissionOutcome::EmitAndFinish(ev) => {
247 Ok(ev)
248 }
249 SubmissionOutcome::Fail(e) => Err(e),
250 }
251 }
252 });
253
254 Ok(mapped.boxed())
255 }
256
257 async fn get_genesis(&self) -> Result<Genesis, NodeClientError> {
258 let genesis_hash = self.api.genesis_hash();
259 let at_block =
260 self.api
261 .at_block(genesis_hash)
262 .await
263 .map_err(|e| NodeClientError::Connection {
264 message: format!(
265 "failed to load genesis block {}: {e}",
266 format_hash(genesis_hash)
267 ),
268 source: Some(Box::new(e)),
269 })?;
270
271 let extrinsics =
272 at_block
273 .extrinsics()
274 .fetch()
275 .await
276 .map_err(|e| NodeClientError::Connection {
277 message: format!("failed to fetch genesis extrinsics: {e}"),
278 source: Some(Box::new(e)),
279 })?;
280
281 let mut transactions: Vec<SerializedTransaction> = Vec::new();
282 for item in extrinsics.iter() {
283 let ext = item.map_err(|e| NodeClientError::Parse {
284 message: format!("failed to decode genesis extrinsic: {e}"),
285 source: Some(Box::new(e)),
286 })?;
287
288 if ext.pallet_name() != MIDNIGHT_PALLET || ext.call_name() != SEND_MN_TRANSACTION {
293 tracing::debug!(
294 target: "moonproof::node-client",
295 "skipping genesis extrinsic #{}: {}.{}",
296 ext.index(),
297 ext.pallet_name(),
298 ext.call_name(),
299 );
300 continue;
301 }
302
303 let (tx_bytes,): (Vec<u8>,) = ext
311 .decode_call_data_fields_unchecked_as()
312 .map_err(|e| NodeClientError::Parse {
313 message: format!(
314 "failed to decode {MIDNIGHT_PALLET}.{SEND_MN_TRANSACTION} args as (Vec<u8>,): {e}"
315 ),
316 source: Some(Box::new(e)),
317 })?;
318 transactions.push(tx_bytes);
319 }
320
321 Ok(Genesis { transactions })
322 }
323}
324
325#[cfg(test)]
326mod tests {
327 use super::*;
328
329 #[test]
330 fn format_hash_renders_canonical_hex_with_prefix() {
331 let bytes = [0xabu8; 32];
332 let hash = H256::from(bytes);
333 let rendered = format_hash(hash);
334 assert!(rendered.starts_with("0x"));
335 assert_eq!(rendered.len(), 2 + 64);
336 assert!(rendered.chars().skip(2).all(|c| c.is_ascii_hexdigit()));
337 }
338
339 #[test]
340 fn midnight_pallet_constants_match_ts_dispatch_names() {
341 assert_eq!(MIDNIGHT_PALLET, "Midnight");
348 assert_eq!(SEND_MN_TRANSACTION, "send_mn_transaction");
349 }
350}