use std::{fmt, future::Future, pin::Pin, sync::Arc};
use tokio::io::{AsyncRead, AsyncWrite};
pub type HostError = Box<dyn std::error::Error + Send + Sync>;
pub trait HttpExchange: Send + Sync {
fn send(&self, request: HttpRequest) -> HttpExchangeFuture<'_>;
}
impl<T: HttpExchange + ?Sized> HttpExchange for Arc<T> {
fn send(&self, request: HttpRequest) -> HttpExchangeFuture<'_> {
(**self).send(request)
}
}
pub type HttpExchangeFuture<'a> =
Pin<Box<dyn Future<Output = Result<HttpAnswer, HostError>> + Send + 'a>>;
#[non_exhaustive]
pub struct HttpRequest {
pub method: &'static str,
pub url: String,
pub headers: Vec<(&'static str, String)>,
pub body: Option<Vec<u8>>,
}
impl fmt::Debug for HttpRequest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let headers: Vec<_> = self
.headers
.iter()
.map(|(name, value)| {
(*name, if *name == "authorization" { "<redacted>" } else { value.as_str() })
})
.collect();
f.debug_struct("HttpRequest")
.field("method", &self.method)
.field("url", &self.url)
.field("headers", &headers)
.field("body", &self.body.as_ref().map(Vec::len))
.finish()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HttpAnswer {
status: u16,
headers: Vec<(String, String)>,
body: Vec<u8>,
}
impl HttpAnswer {
pub fn new(status: u16, body: impl Into<Vec<u8>>) -> Self {
Self { status, headers: Vec::new(), body: body.into() }
}
#[must_use]
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.push((name.into(), value.into()));
self
}
#[must_use]
pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
self.body = body.into();
self
}
pub(crate) fn header_value(&self, name: &str) -> Option<&str> {
self.headers
.iter()
.find(|(candidate, _)| candidate.eq_ignore_ascii_case(name))
.map(|(_, value)| value.as_str())
}
pub(crate) const fn status(&self) -> u16 {
self.status
}
pub(crate) fn into_body(self) -> Vec<u8> {
self.body
}
}
pub trait HostStream: AsyncRead + AsyncWrite + Send + Sync + Unpin {}
impl<T: AsyncRead + AsyncWrite + Send + Sync + Unpin> HostStream for T {}
pub trait StreamConnector: Send + Sync {
fn connect<'a>(&'a self, host: &'a str, port: u16) -> StreamFuture<'a>;
}
impl<T: StreamConnector + ?Sized> StreamConnector for Arc<T> {
fn connect<'a>(&'a self, host: &'a str, port: u16) -> StreamFuture<'a> {
(**self).connect(host, port)
}
}
pub type StreamFuture<'a> =
Pin<Box<dyn Future<Output = Result<Box<dyn HostStream>, HostError>> + Send + 'a>>;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Transaction {
pub id: String,
pub chain_id: u64,
pub to: alloy_primitives::Address,
pub data: Vec<u8>,
pub value: alloy_primitives::U256,
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum SendError {
#[error("transaction not sent")]
NotSent(#[source] HostError),
#[error("transaction outcome unknown")]
Unknown(#[source] HostError),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SendStatus {
Sent(alloy_primitives::B256),
NotSent,
Unknown,
}
pub trait TransactionSender: Send + Sync {
fn send(&self, transaction: Transaction) -> SendFuture<'_>;
fn status<'a>(&'a self, id: &'a str) -> StatusFuture<'a> {
let _ = id;
Box::pin(async { Ok(SendStatus::Unknown) })
}
}
impl<T: TransactionSender + ?Sized> TransactionSender for Arc<T> {
fn send(&self, transaction: Transaction) -> SendFuture<'_> {
(**self).send(transaction)
}
fn status<'a>(&'a self, id: &'a str) -> StatusFuture<'a> {
(**self).status(id)
}
}
pub type SendFuture<'a> =
Pin<Box<dyn Future<Output = Result<alloy_primitives::B256, SendError>> + Send + 'a>>;
pub type StatusFuture<'a> =
Pin<Box<dyn Future<Output = Result<SendStatus, HostError>> + Send + 'a>>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum BlockTag {
Latest,
Finalized,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ChainCall {
pub chain_id: u64,
pub to: alloy_primitives::Address,
pub data: Vec<u8>,
pub block: BlockTag,
}
pub trait ChainReader: Send + Sync {
fn call(&self, call: ChainCall) -> ChainCallFuture<'_>;
}
impl<T: ChainReader + ?Sized> ChainReader for Arc<T> {
fn call(&self, call: ChainCall) -> ChainCallFuture<'_> {
(**self).call(call)
}
}
pub type ChainCallFuture<'a> =
Pin<Box<dyn Future<Output = Result<Vec<u8>, HostError>> + Send + 'a>>;