use super::{Chain, Family, Identifier, Origin, Token};
use crate::{
domain::{Amount, ExactDecimal, Timestamp},
error::Error,
};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "TransactionIdFields")]
pub struct TransactionId {
chain: Chain,
identifier: String,
}
impl TransactionId {
pub fn new(chain: Chain, text: &str) -> Result<Self, Error> {
if text.len() > 128 {
return Err(super::invalid_identity());
}
let identifier = match chain.family() {
Family::Evm => crate::domain::BlockHash::parse(text)
.map_err(|_| super::invalid_identity())?
.to_string(),
Family::Solana | Family::Move => {
let size = if chain.family() == Family::Solana {
64
} else {
32
};
let mut bytes = [0_u8; 64];
if bs58::decode(text).onto(&mut bytes[..size]).ok() != Some(size)
|| bs58::encode(&bytes[..size]).into_string() != text
{
return Err(super::invalid_identity());
}
text.to_owned()
}
Family::Utxo | Family::Tron | Family::Stellar => {
if text.len() != 64 || !text.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(super::invalid_identity());
}
text.to_ascii_lowercase()
}
};
Ok(Self { chain, identifier })
}
#[must_use]
pub const fn chain(&self) -> Chain {
self.chain
}
#[must_use]
pub fn identifier(&self) -> &str {
&self.identifier
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct TransactionIdFields {
chain: Chain,
identifier: String,
}
impl TryFrom<TransactionIdFields> for TransactionId {
type Error = Error;
fn try_from(v: TransactionIdFields) -> Result<Self, Error> {
Self::new(v.chain, &v.identifier)
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct TransferId(String);
impl TransferId {
pub fn new(text: &str) -> Result<Self, Error> {
let value = crate::domain::BlockHash::parse(text).map_err(|_| super::invalid_identity())?;
Ok(Self(value.to_string()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl TryFrom<String> for TransferId {
type Error = Error;
fn try_from(v: String) -> Result<Self, Error> {
Self::new(&v)
}
}
impl From<TransferId> for String {
fn from(v: TransferId) -> Self {
v.0
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(
tag = "kind",
content = "value",
rename_all = "snake_case",
deny_unknown_fields
)]
pub enum StatusSelector {
SendingTransaction(TransactionId),
ReceivingTransaction(TransactionId),
ProviderTransfer(TransferId),
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "StatusQueryFields")]
pub struct StatusQuery {
from: Chain,
to: Chain,
selector: StatusSelector,
bridge: Option<Identifier>,
}
impl StatusQuery {
pub fn new(
from: Chain,
to: Chain,
selector: StatusSelector,
bridge: Option<Identifier>,
) -> Result<Self, Error> {
if matches!(&selector,StatusSelector::SendingTransaction(id) if id.chain()!=from)
|| matches!(&selector,StatusSelector::ReceivingTransaction(id) if id.chain()!=to)
{
return Err(super::invalid_identity());
}
Ok(Self {
from,
to,
selector,
bridge,
})
}
#[must_use]
pub const fn from(&self) -> Chain {
self.from
}
#[must_use]
pub const fn to(&self) -> Chain {
self.to
}
#[must_use]
pub const fn selector(&self) -> &StatusSelector {
&self.selector
}
#[must_use]
pub const fn bridge(&self) -> Option<&Identifier> {
self.bridge.as_ref()
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct StatusQueryFields {
from: Chain,
to: Chain,
selector: StatusSelector,
bridge: Option<Identifier>,
}
impl TryFrom<StatusQueryFields> for StatusQuery {
type Error = Error;
fn try_from(v: StatusQueryFields) -> Result<Self, Error> {
Self::new(v.from, v.to, v.selector, v.bridge)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Progress {
NotFound,
Invalid,
Pending,
Done,
Failed,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReceivingRole {
Unreported,
Destination,
Refund,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ObservedLeg {
pub tool: Identifier,
pub from_token: Token,
pub from_amount: Amount,
pub to_token: Token,
pub to_amount: Amount,
pub bridged_amount: Option<Amount>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TransactionData {
pub chain: Chain,
pub id: Option<TransactionId>,
pub token: Option<Token>,
pub amount: Option<Amount>,
pub timestamp: Option<Timestamp>,
pub value: Option<Amount>,
pub gas_price: Option<ExactDecimal>,
pub gas_used: Option<Amount>,
pub gas_token: Option<Token>,
pub gas_amount: Option<Amount>,
pub gas_amount_usd: Option<ExactDecimal>,
pub included_legs: Option<Vec<ObservedLeg>>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "TransactionData", into = "TransactionData")]
pub struct Transaction(TransactionData);
impl Transaction {
pub fn new(data: TransactionData) -> Result<Self, Error> {
if data.id.as_ref().is_some_and(|id| id.chain() != data.chain)
|| data
.token
.as_ref()
.is_some_and(|t| t.data().asset.chain() != data.chain)
|| data
.gas_token
.as_ref()
.is_some_and(|t| t.data().asset.chain() != data.chain)
|| data.value.is_some_and(|a| a.decimals().is_some())
|| data.gas_used.is_some_and(|a| a.decimals().is_some())
|| data
.gas_price
.as_ref()
.is_some_and(ExactDecimal::is_negative)
|| data
.gas_amount_usd
.as_ref()
.is_some_and(ExactDecimal::is_negative)
{
return Err(super::invalid_record());
}
for (amount, token) in [
(data.amount, &data.token),
(data.gas_amount, &data.gas_token),
] {
if let Some(amount) = amount
&& amount.decimals() != token.as_ref().map(|t| t.data().decimals)
{
return Err(super::invalid_record());
}
}
if let Some(legs) = &data.included_legs
&& (legs.len() > 256
|| legs.iter().any(|l| {
l.from_amount.decimals() != Some(l.from_token.data().decimals)
|| l.to_amount.decimals() != Some(l.to_token.data().decimals)
|| l.bridged_amount
.is_some_and(|a| a.decimals() != Some(l.to_token.data().decimals))
}))
{
return Err(super::invalid_record());
}
Ok(Self(data))
}
#[must_use]
pub const fn data(&self) -> &TransactionData {
&self.0
}
}
impl TryFrom<TransactionData> for Transaction {
type Error = Error;
fn try_from(v: TransactionData) -> Result<Self, Error> {
Self::new(v)
}
}
impl From<Transaction> for TransactionData {
fn from(v: Transaction) -> Self {
v.0
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StatusData {
pub progress: Progress,
pub substatus: Option<Identifier>,
pub tool: Option<Identifier>,
pub transfer_id: Option<TransferId>,
pub sending: Option<Transaction>,
pub receiving: Option<Transaction>,
pub fees: Option<Vec<super::Fee>>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "StatusFields")]
pub struct Status {
query: StatusQuery,
data: StatusData,
origin: Origin,
}
impl Status {
pub fn new(query: StatusQuery, data: StatusData, origin: Origin) -> Result<Self, Error> {
let refund = data
.substatus
.as_ref()
.is_some_and(|s| matches!(s.as_str(), "REFUNDED" | "REFUND_IN_PROGRESS"));
if data
.sending
.as_ref()
.is_some_and(|s| s.data().chain != query.from)
|| data.receiving.as_ref().is_some_and(|r| {
r.data().chain != query.to && !(refund && r.data().chain == query.from)
})
|| data.fees.as_ref().is_some_and(|v| v.len() > 128)
{
return Err(super::invalid_record());
}
let reported = match &query.selector {
StatusSelector::SendingTransaction(expected) => Some((expected, data.sending.as_ref())),
StatusSelector::ReceivingTransaction(expected) => {
Some((expected, data.receiving.as_ref()))
}
StatusSelector::ProviderTransfer(expected) => {
if data.transfer_id.as_ref().is_some_and(|id| id != expected) {
return Err(super::invalid_record());
}
None
}
};
if let Some((expected, Some(actual))) = reported
&& actual.data().id.as_ref().is_some_and(|id| id != expected)
{
return Err(super::invalid_record());
}
Ok(Self {
query,
data,
origin,
})
}
#[must_use]
pub const fn query(&self) -> &StatusQuery {
&self.query
}
#[must_use]
pub const fn data(&self) -> &StatusData {
&self.data
}
#[must_use]
pub const fn origin(&self) -> &Origin {
&self.origin
}
#[must_use]
pub fn receiving_role(&self) -> ReceivingRole {
match &self.data.receiving {
None => ReceivingRole::Unreported,
Some(r)
if r.data().chain == self.query.from
&& self.data.substatus.as_ref().is_some_and(|s| {
matches!(s.as_str(), "REFUNDED" | "REFUND_IN_PROGRESS")
}) =>
{
ReceivingRole::Refund
}
Some(_) => ReceivingRole::Destination,
}
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct StatusFields {
query: StatusQuery,
data: StatusData,
origin: Origin,
}
impl TryFrom<StatusFields> for Status {
type Error = Error;
fn try_from(v: StatusFields) -> Result<Self, Error> {
Self::new(v.query, v.data, v.origin)
}
}