use super::{
AccountState, Address, AddressFormat, Boc, Currency, Cursor, ExtraCurrency, Hash, LogicalTime,
Nanotons,
};
use crate::{domain::Amount, error::Error};
use serde::{Deserialize, Serialize};
use tycho_types::{
cell::{Cell, Load},
models::{self, IntAddr, MsgInfo, TxInfo},
};
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Message {
boc: Boc,
}
impl Message {
#[must_use]
pub const fn new(boc: Boc) -> Self {
Self { boc }
}
#[must_use]
pub const fn boc(&self) -> &Boc {
&self.boc
}
pub fn hash(&self) -> Result<Hash, Error> {
self.boc.hash()
}
pub fn forwarding_fee(&self) -> Result<Option<Nanotons>, Error> {
let root = self.boc.root()?;
let mut slice = root.as_slice().map_err(|_| super::invalid_record())?;
let Ok(message) = models::Message::load_from(&mut slice) else {
return Ok(None);
};
if !slice.is_empty() {
return Ok(None);
}
match message.info {
MsgInfo::Int(info) => Nanotons::new(info.fwd_fee.into_inner()).map(Some),
MsgInfo::ExtIn(_) | MsgInfo::ExtOut(_) => Ok(Some(Nanotons::ZERO)),
}
}
pub fn info(&self) -> Result<MessageInfo, Error> {
let root = self.boc.root()?;
let mut slice = root.as_slice().map_err(|_| super::invalid_record())?;
let Ok(message) = models::Message::load_from(&mut slice) else {
return Ok(MessageInfo::Uninterpreted);
};
if !slice.is_empty() {
return Ok(MessageInfo::Uninterpreted);
}
match message.info {
MsgInfo::Int(info) => {
let (Some(source), Some(destination)) = (standard(&info.src), standard(&info.dst))
else {
return Ok(MessageInfo::Uninterpreted);
};
Ok(MessageInfo::Internal {
source,
destination,
value: currency(&info.value)?,
bounce: info.bounce,
bounced: info.bounced,
created_lt: info.created_lt,
created_unix_seconds: info.created_at,
})
}
MsgInfo::ExtIn(info) => {
let Some(destination) = standard(&info.dst) else {
return Ok(MessageInfo::Uninterpreted);
};
Ok(MessageInfo::ExternalIncoming {
destination,
import_fee: Nanotons::new(info.import_fee.into_inner())?,
})
}
MsgInfo::ExtOut(info) => {
let Some(source) = standard(&info.src) else {
return Ok(MessageInfo::Uninterpreted);
};
Ok(MessageInfo::ExternalOutgoing {
source,
created_lt: info.created_lt,
created_unix_seconds: info.created_at,
})
}
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum MessageInfo {
Internal {
source: Address,
destination: Address,
value: Currency,
bounce: bool,
bounced: bool,
created_lt: u64,
created_unix_seconds: u32,
},
ExternalIncoming {
destination: Address,
import_fee: Nanotons,
},
ExternalOutgoing {
source: Address,
created_lt: u64,
created_unix_seconds: u32,
},
Uninterpreted,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Compute {
Skipped {
reason: ComputeSkip,
},
Executed {
success: bool,
exit_code: i32,
gas_fees: Nanotons,
},
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ComputeSkip {
NoState,
BadState,
NoGas,
Suspended,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Action {
pub success: bool,
pub valid: bool,
pub no_funds: bool,
pub result_code: i32,
pub messages_created: u16,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Execution {
Ordinary {
aborted: bool,
destroyed: bool,
compute: Compute,
action: Option<Action>,
},
TickTock {
aborted: bool,
destroyed: bool,
compute: Compute,
action: Option<Action>,
},
Uninterpreted {
prefix: u8,
description: Boc,
},
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SourceMessageFees {
pub message_hash: Hash,
pub forwarding_fee: Nanotons,
pub source_ihr_fee: Nanotons,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "ProviderFeesFields")]
pub struct ProviderFees {
aggregate: Nanotons,
storage: Nanotons,
other: Nanotons,
outgoing: Vec<SourceMessageFees>,
}
impl ProviderFees {
pub fn new(
aggregate: Nanotons,
storage: Nanotons,
other: Nanotons,
outgoing: Vec<SourceMessageFees>,
) -> Result<Self, Error> {
if outgoing.len() > 256 || storage.raw().checked_add(other.raw()) != Some(aggregate.raw()) {
return Err(super::invalid_record());
}
Ok(Self {
aggregate,
storage,
other,
outgoing,
})
}
#[must_use]
pub const fn aggregate(&self) -> Nanotons {
self.aggregate
}
#[must_use]
pub const fn storage(&self) -> Nanotons {
self.storage
}
#[must_use]
pub const fn other(&self) -> Nanotons {
self.other
}
#[must_use]
pub fn outgoing(&self) -> &[SourceMessageFees] {
&self.outgoing
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ProviderFeesFields {
aggregate: Nanotons,
storage: Nanotons,
other: Nanotons,
outgoing: Vec<SourceMessageFees>,
}
impl TryFrom<ProviderFeesFields> for ProviderFees {
type Error = Error;
fn try_from(v: ProviderFeesFields) -> Result<Self, Error> {
Self::new(v.aggregate, v.storage, v.other, v.outgoing)
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "TransactionFields")]
pub struct Transaction {
account: Address,
boc: Boc,
cursor: Cursor,
previous: Option<Cursor>,
created_unix_seconds: u32,
fees: Currency,
provider_fees: Option<ProviderFees>,
original_state: AccountState,
end_state: AccountState,
incoming: Option<Message>,
outgoing: Vec<Message>,
execution: Execution,
}
impl Transaction {
pub fn decode(account: Address, boc: Boc) -> Result<Self, Error> {
let root = boc.root()?;
let mut slice = root.as_slice().map_err(|_| super::invalid_record())?;
let tx = models::Transaction::load_from(&mut slice).map_err(|_| super::invalid_record())?;
if !slice.is_empty() || tx.account.0 != *account.account().as_bytes() {
return Err(super::invalid_record());
}
let mut update = tx
.state_update
.inner()
.as_slice()
.map_err(|_| super::invalid_record())?;
models::HashUpdate::load_from(&mut update).map_err(|_| super::invalid_record())?;
if !update.is_empty() {
return Err(super::invalid_record());
}
let cursor = Cursor::new(LogicalTime::new(tx.lt)?, boc.hash()?)?;
let previous = if tx.prev_trans_lt == 0 {
if tx.prev_trans_hash.0 != [0; 32] {
return Err(super::invalid_record());
}
None
} else {
if tx.prev_trans_lt >= tx.lt {
return Err(super::invalid_record());
}
Some(Cursor::new(
LogicalTime::new(tx.prev_trans_lt)?,
Hash::from_bytes(tx.prev_trans_hash.0),
)?)
};
let incoming = tx.in_msg.as_ref().map(message).transpose()?;
if tx.out_msg_count.into_inner() > 256 {
return Err(super::invalid_record());
}
let mut outgoing = Vec::new();
for entry in tx.out_msgs.iter() {
let (index, cell) = entry.map_err(|_| super::invalid_record())?;
if outgoing.len() >= 256 {
return Err(super::invalid_record());
}
if usize::from(index.into_inner()) != outgoing.len() {
return Err(super::invalid_record());
}
outgoing.push(message(&cell)?);
}
if outgoing.len() != usize::from(tx.out_msg_count.into_inner()) {
return Err(super::invalid_record());
}
let execution = execution(&tx)?;
Ok(Self {
account,
boc,
cursor,
previous,
created_unix_seconds: tx.now,
fees: currency(&tx.total_fees)?,
provider_fees: None,
original_state: account_state(tx.orig_status),
end_state: account_state(tx.end_status),
incoming,
outgoing,
execution,
})
}
pub fn with_provider_fees(mut self, fees: ProviderFees) -> Result<Self, Error> {
if fees.outgoing.len() != self.outgoing.len() {
return Err(super::invalid_record());
}
let mut aggregate = self.fees.native().raw();
for (source, message) in fees.outgoing.iter().zip(&self.outgoing) {
if source.message_hash != message.hash()?
|| message
.forwarding_fee()?
.is_some_and(|fee| fee != source.forwarding_fee)
{
return Err(super::invalid_record());
}
aggregate = aggregate
.checked_add(source.forwarding_fee.raw())
.and_then(|v| v.checked_add(source.source_ihr_fee.raw()))
.ok_or_else(super::invalid_record)?;
}
if aggregate != fees.aggregate.raw() {
return Err(super::invalid_record());
}
self.provider_fees = Some(fees);
Ok(self)
}
#[must_use]
pub const fn provider_fees(&self) -> Option<&ProviderFees> {
self.provider_fees.as_ref()
}
#[must_use]
pub const fn account(&self) -> Address {
self.account
}
#[must_use]
pub const fn boc(&self) -> &Boc {
&self.boc
}
#[must_use]
pub const fn cursor(&self) -> Cursor {
self.cursor
}
#[must_use]
pub const fn previous(&self) -> Option<Cursor> {
self.previous
}
#[must_use]
pub const fn created_unix_seconds(&self) -> u32 {
self.created_unix_seconds
}
#[must_use]
pub const fn fees(&self) -> &Currency {
&self.fees
}
#[must_use]
pub const fn original_state(&self) -> AccountState {
self.original_state
}
#[must_use]
pub const fn end_state(&self) -> AccountState {
self.end_state
}
#[must_use]
pub const fn incoming(&self) -> Option<&Message> {
self.incoming.as_ref()
}
#[must_use]
pub fn outgoing(&self) -> &[Message] {
&self.outgoing
}
#[must_use]
pub const fn execution(&self) -> &Execution {
&self.execution
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct TransactionFields {
account: Address,
boc: Boc,
cursor: Cursor,
previous: Option<Cursor>,
created_unix_seconds: u32,
fees: Currency,
provider_fees: Option<ProviderFees>,
original_state: AccountState,
end_state: AccountState,
incoming: Option<Message>,
outgoing: Vec<Message>,
execution: Execution,
}
impl TryFrom<TransactionFields> for Transaction {
type Error = Error;
fn try_from(v: TransactionFields) -> Result<Self, Error> {
let mut tx = Self::decode(v.account, v.boc)?;
if let Some(fees) = v.provider_fees {
tx = tx.with_provider_fees(fees)?;
}
if tx.cursor != v.cursor
|| tx.previous != v.previous
|| tx.created_unix_seconds != v.created_unix_seconds
|| tx.fees != v.fees
|| tx.original_state != v.original_state
|| tx.end_state != v.end_state
|| tx.incoming != v.incoming
|| tx.outgoing != v.outgoing
|| tx.execution != v.execution
{
return Err(super::invalid_record());
}
Ok(tx)
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TransactionStatus {
transaction: Transaction,
}
impl TransactionStatus {
#[must_use]
pub const fn new(transaction: Transaction) -> Self {
Self { transaction }
}
#[must_use]
pub const fn transaction(&self) -> &Transaction {
&self.transaction
}
}
pub(crate) fn standard(address: &IntAddr) -> Option<Address> {
match address {
IntAddr::Std(s) if s.anycast.is_none() => Some(Address::new(
s.workchain,
Hash::from_bytes(s.address.0),
AddressFormat::Raw,
)),
_ => None,
}
}
pub(crate) fn currency(value: &models::CurrencyCollection) -> Result<Currency, Error> {
let mut extra = Vec::new();
for entry in value.other.as_dict().iter() {
let (id, value) = entry.map_err(|_| super::invalid_record())?;
if extra.len() >= 256 {
return Err(super::invalid_record());
}
extra.push(ExtraCurrency {
id,
amount: Amount::from_decimal(&value.to_string(), None)?,
});
}
Currency::new(Nanotons::new(value.tokens.into_inner())?, extra)
}
fn message(cell: &Cell) -> Result<Message, Error> {
Ok(Message::new(Boc::from_cell(cell)?))
}
fn account_state(state: models::AccountStatus) -> AccountState {
match state {
models::AccountStatus::Uninit => AccountState::Uninitialized,
models::AccountStatus::Frozen => AccountState::Frozen,
models::AccountStatus::Active => AccountState::Active,
models::AccountStatus::NotExists => AccountState::Nonexistent,
}
}
fn compute(phase: models::ComputePhase) -> Result<Compute, Error> {
Ok(match phase {
models::ComputePhase::Skipped(p) => Compute::Skipped {
reason: match p.reason {
models::ComputePhaseSkipReason::NoState => ComputeSkip::NoState,
models::ComputePhaseSkipReason::BadState => ComputeSkip::BadState,
models::ComputePhaseSkipReason::NoGas => ComputeSkip::NoGas,
models::ComputePhaseSkipReason::Suspended => ComputeSkip::Suspended,
},
},
models::ComputePhase::Executed(p) => Compute::Executed {
success: p.success,
exit_code: p.exit_code,
gas_fees: Nanotons::new(p.gas_fees.into_inner())?,
},
})
}
fn action(phase: Option<models::ActionPhase>) -> Option<Action> {
phase.map(|p| Action {
success: p.success,
valid: p.valid,
no_funds: p.no_funds,
result_code: p.result_code,
messages_created: p.messages_created,
})
}
fn execution(tx: &models::Transaction) -> Result<Execution, Error> {
let cell = tx.info.inner();
let mut slice = cell.as_slice().map_err(|_| super::invalid_record())?;
let prefix = slice
.load_small_uint(3)
.map_err(|_| super::invalid_record())?;
if prefix != 0 && prefix != 1 {
return Ok(Execution::Uninterpreted {
prefix,
description: Boc::from_cell(cell)?,
});
}
if prefix == 0 && slice.load_bit().map_err(|_| super::invalid_record())? {
return Ok(Execution::Uninterpreted {
prefix,
description: Boc::from_cell(cell)?,
});
}
let mut full = cell.as_slice().map_err(|_| super::invalid_record())?;
let info = TxInfo::load_from(&mut full).map_err(|_| super::invalid_record())?;
if !full.is_empty() {
return Err(super::invalid_record());
}
Ok(match info {
TxInfo::Ordinary(p) => Execution::Ordinary {
aborted: p.aborted,
destroyed: p.destroyed,
compute: compute(p.compute_phase)?,
action: action(p.action_phase),
},
TxInfo::TickTock(p) => Execution::TickTock {
aborted: p.aborted,
destroyed: p.destroyed,
compute: compute(p.compute_phase)?,
action: action(p.action_phase),
},
})
}