use std::sync::Arc;
use std::time::Duration;
use crate::error::SdkError;
use crate::types::{Receipt, TxHash};
use super::provider_trait::Provider;
pub const DEFAULT_POLL_INTERVAL: Duration = Duration::from_millis(250);
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60);
#[derive(Clone)]
pub struct PendingTx {
hash: TxHash,
provider: Arc<dyn Provider>,
poll_interval: Duration,
timeout: Duration,
}
impl PendingTx {
#[must_use]
pub fn new(hash: TxHash, provider: Arc<dyn Provider>) -> Self {
Self {
hash,
provider,
poll_interval: DEFAULT_POLL_INTERVAL,
timeout: DEFAULT_TIMEOUT,
}
}
#[must_use]
pub fn with_poll_interval(mut self, interval: Duration) -> Self {
self.poll_interval = interval;
self
}
#[must_use]
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
#[must_use]
pub fn hash(&self) -> TxHash {
self.hash
}
pub async fn wait_for_receipt(&self) -> Result<Receipt, SdkError> {
let deadline = std::time::Instant::now() + self.timeout;
let expected_hex = format!("0x{}", hex::encode(self.hash.as_bytes()));
loop {
if let Some(receipt) = self.provider.get_transaction_receipt(&self.hash).await? {
if !receipt
.tx_hash
.trim_start_matches("0x")
.eq_ignore_ascii_case(expected_hex.trim_start_matches("0x"))
{
return Err(SdkError::InvalidResponse(format!(
"receipt tx_hash {} doesn't match polled hash {expected_hex}",
receipt.tx_hash
)));
}
return Ok(receipt);
}
if std::time::Instant::now() >= deadline {
return Err(SdkError::Timeout(format!(
"tx {expected_hex} did not commit within {:?}",
self.timeout
)));
}
tokio::time::sleep(self.poll_interval).await;
}
}
}
impl std::fmt::Debug for PendingTx {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PendingTx")
.field("hash", &self.hash)
.field("poll_interval", &self.poll_interval)
.field("timeout", &self.timeout)
.finish()
}
}