use alloy_primitives::{Address, B256};
use serde::{Deserialize, Serialize};
use super::Bridges;
use crate::{
Error, Result,
error::{ErrorCode, Reason},
model::{Bridge, BridgeFunding},
transport::{Call, ops},
types::{Amount, BridgeId, ClientId, MoveId},
};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BridgeRequest {
client_bridge_id: ClientId,
amount_in: Amount,
#[serde(default, skip_serializing_if = "Option::is_none")]
from_wallet: Option<WalletSource>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct WalletSource {
chain_id: u64,
token: Address,
}
impl BridgeRequest {
pub fn new(id: ClientId, amount_in: Amount) -> Self {
Self { client_bridge_id: id, amount_in, from_wallet: None }
}
#[must_use]
pub fn from_wallet(mut self, chain_id: u64, token: Address) -> Self {
self.from_wallet = Some(WalletSource { chain_id, token });
self
}
}
#[derive(Serialize)]
struct Report {
#[serde(skip_serializing_if = "Option::is_none")]
tx_hash: Option<B256>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
unsent: bool,
}
impl Bridges<'_> {
pub async fn create(&self, move_id: MoveId, request: &BridgeRequest) -> Result<Bridge> {
let call = Call::new(&ops::CREATE_BRIDGE).segment(move_id).json(request)?;
self.inner.send(call, self.auth).await
}
pub async fn get(&self, id: BridgeId) -> Result<Bridge> {
self.inner.send(Call::new(&ops::GET_BRIDGE).segment(id), self.auth).await
}
pub async fn funding(&self, id: BridgeId) -> Result<BridgeFunding> {
self.inner.send(Call::new(&ops::GET_BRIDGE_FUNDING).segment(id), self.auth).await
}
pub async fn fence(&self, id: BridgeId) -> Result<Bridge> {
let body = Report { tx_hash: None, unsent: false };
let call = Call::new(&ops::FENCE_BRIDGE).segment(id).json(&body)?;
self.inner.send(call, self.auth).await.map_err(|error| {
let fenced = error.api().is_some_and(|api| {
*api.code() == ErrorCode::StateConflict && api.reason() == Some(&Reason::Fenced)
});
if fenced { Error::DepositFenced(id) } else { error }
})
}
pub async fn report_transaction(&self, id: BridgeId, tx_hash: B256) -> Result<Bridge> {
self.report(id, &Report { tx_hash: Some(tx_hash), unsent: false }).await
}
pub async fn report_unsent(&self, id: BridgeId) -> Result<Bridge> {
self.report(id, &Report { tx_hash: None, unsent: true }).await
}
async fn report(&self, id: BridgeId, body: &Report) -> Result<Bridge> {
let call = Call::new(&ops::REPORT_BRIDGE_TRANSACTION).segment(id).json(body)?;
self.inner.send(call, self.auth).await
}
}
#[cfg(test)]
mod tests;