use alloy_primitives::{Address, B256, U256};
use serde::{Deserialize, Serialize};
use tracing::Instrument as _;
use uuid::Uuid;
use super::{
conversion::{APPROVE, DEADLINE_WINDOW_SECONDS, check_conversion_capability},
records,
};
use crate::{
Error, Result, SendError, SendStatus, Session, Transaction, TransactionSender,
api::DirectRequest,
deployments,
model::{BridgeFunding, DirectKind, DirectOperation, DirectState, EscrowChain},
protocol::{
checks::{
deployment,
details::{self, changed, differs, stale, unsupported},
},
gmx,
},
types::{Amount, VenueId},
};
mod inspect;
pub use inspect::{DirectInspection, DirectStep, check_direct_amounts, inspect_direct_transaction};
const DEPOSIT: [u8; 4] = [0xfc, 0x95, 0x98, 0xe8];
const FUNDS_AHEAD_MS: i64 = 15_000;
const FUNDS_AGE_MS: i64 = 120_000;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum DirectOutcome {
Operation(Box<DirectOperation>),
Waiting(DirectWait),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DirectWait {
Approval,
NotSent,
Unknown,
}
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
struct Identity {
id: Uuid,
nonce: Amount,
deadline: Amount,
escrow: Address,
}
#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize)]
struct Asked {
#[serde(default, skip_serializing_if = "Option::is_none")]
hash: Option<B256>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
unsent: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
fenced: bool,
}
fn is_final(state: &DirectState) -> bool {
matches!(state, DirectState::Confirmed | DirectState::Failed | DirectState::Expired)
}
impl Session {
pub async fn direct_transfer(
&self,
request: &DirectRequest,
sender: &dyn TransactionSender,
) -> Result<DirectOutcome> {
let span = tracing::info_span!(
"lamarge.direct",
client_operation_id = %request.client_operation_id,
);
run(self, request, Some(sender)).instrument(span).await
}
}
#[expect(clippy::too_many_lines, reason = "the TypeScript directTransfer(), step by step")]
pub(super) async fn run(
session: &Session,
request: &DirectRequest,
sender: Option<&dyn TransactionSender>,
) -> Result<DirectOutcome> {
request.validate()?;
if request.owner != session.address() {
return Err(Error::InvalidRequest(
"a direct operation of the session's own address".into(),
));
}
let journal = session.journal();
let key = |record: &str| {
session.record_key(&format!("direct:{}{record}", request.client_operation_id))
};
let _turn = journal.lock(&key("")).await;
match records::load::<DirectRequest>(journal, &key(":request")).await? {
Some(saved) if saved != *request => {
let message = format!("direct {} names another operation", request.client_operation_id);
return Err(Error::InvalidRequest(message.into()));
}
Some(_) => {}
None => records::save(journal, &key(":request"), request, false).await?,
}
let directs = session.directs();
let created = directs.create(request).await?;
check(session, &created, request)?;
let identity = Identity {
id: created.id,
nonce: created.nonce,
deadline: created.deadline,
escrow: created.escrow,
};
match records::load::<Identity>(journal, &key(":identity")).await? {
Some(saved) if saved != identity => return Err(changed(details::DIRECT).into()),
Some(_) => {}
None => records::save(journal, &key(":identity"), &identity, false).await?,
}
let read = || async {
let operation = directs.get(identity.id).await?;
check(session, &operation, request)?;
let same = (operation.id, operation.nonce, operation.deadline, operation.escrow)
== (identity.id, identity.nonce, identity.deadline, identity.escrow);
if same { Ok(operation) } else { Err(Error::from(changed(details::DIRECT))) }
};
let sent_key = key(":sent");
let step = request.kind.as_str();
let mut sent = records::load::<Asked>(journal, &sent_key).await?;
if let Some(asked) = &mut sent {
if asked.fenced && asked.hash.is_none() && !asked.unsent {
match status(sender, &transaction_id(identity.id, step)).await {
SendStatus::Sent(hash) => asked.hash = Some(hash),
SendStatus::NotSent => asked.unsent = true,
_ => {}
}
records::save(journal, &sent_key, asked, true).await?;
}
if let Some(hash) = asked.hash
&& !created.attempts.iter().any(|seen| seen.parse() == Ok(hash))
{
directs.report_transaction(identity.id, hash).await?;
}
}
let operation = read().await?;
if is_final(&operation.state) {
return Ok(DirectOutcome::Operation(Box::new(operation)));
}
let retry = request.kind == DirectKind::Deposit
&& sent.is_some_and(|asked| asked.unsent && asked.hash.is_none());
if !retry && (operation.state != DirectState::Prepared || sent.is_some()) {
return Ok(DirectOutcome::Operation(Box::new(operation)));
}
if !in_window(operation.deadline.get(), session.transport().now().timestamp()) {
return Err(stale(details::DEADLINE).into());
}
let chain = enabled_chain(session, &request.venue).await?;
if chain.escrow != operation.escrow {
return Err(differs(details::ESCROW).into());
}
let capable = match request.kind {
DirectKind::Deposit => chain.direct_deposit,
_ => chain.direct_withdrawal,
};
if capable != Some(true) {
return Err(unsupported(details::VENUE).into());
}
if request.token != chain.token {
check_conversion_capability(&chain)?;
}
let sender = sender.ok_or(Error::TransactionSenderRequired)?;
let read_funds = || async {
let funds = directs.funding(identity.id).await?;
check_funds(session, &funds, request, operation.escrow)?;
Ok::<_, Error>(funds)
};
let funds = read_funds().await?;
if request.kind == DirectKind::Deposit && funds.allowance < request.amount {
let approval =
Approval { id: transaction_id(identity.id, "approve"), key: key(":approval") };
if let Some(wait) = approve(session, sender, &operation, &approval).await? {
return Ok(DirectOutcome::Waiting(wait));
}
if read_funds().await?.allowance < request.amount {
return Ok(DirectOutcome::Waiting(DirectWait::Approval));
}
}
let fenced = Asked { fenced: true, ..Asked::default() };
if !retry {
records::save(journal, &sent_key, &Asked::default(), false).await?;
directs.fence(identity.id).await?;
}
records::save(journal, &sent_key, &fenced, true).await?;
let transaction = Transaction {
id: transaction_id(identity.id, step),
chain_id: operation.chain_id,
to: target(&operation),
data: calldata(&operation)?,
value: U256::ZERO,
};
match sender.send(transaction).await {
Ok(hash) => {
records::save(journal, &sent_key, &Asked { hash: Some(hash), ..fenced }, true).await?;
directs.report_transaction(identity.id, hash).await?;
}
Err(SendError::NotSent(error)) => {
tracing::info!(%error, step, "direct transaction not sent");
records::save(journal, &sent_key, &Asked { unsent: true, ..fenced }, true).await?;
return Ok(DirectOutcome::Waiting(DirectWait::NotSent));
}
Err(error) => {
tracing::warn!(%error, step, "direct transaction outcome unknown");
return Ok(DirectOutcome::Waiting(DirectWait::Unknown));
}
}
Ok(DirectOutcome::Operation(Box::new(read().await?)))
}
fn check(session: &Session, operation: &DirectOperation, request: &DirectRequest) -> Result<()> {
let chain = deployments::chain(&request.venue).ok_or(unsupported(details::VENUE))?;
let pinned = deployments::escrow(chain.id, session.escrow_environment());
let owner = session.address();
let ok = operation.chain_id == chain.id
&& pinned == Some(operation.escrow)
&& operation.client_operation_id == request.client_operation_id
&& operation.venue == request.venue
&& operation.kind == request.kind
&& operation.owner == owner
&& request.owner == owner
&& operation.recipient == request.recipient
&& operation.token == request.token
&& operation.amount == request.amount
&& operation.min_out == request.min_out;
if !ok {
return Err(changed(details::DIRECT).into());
}
let deposit = request.kind == DirectKind::Deposit;
check_direct_amounts(&request.venue, request.token, request.amount, request.min_out, deposit)?;
calldata(operation)?;
if operation.state == DirectState::Confirmed
&& (operation.tx_hash.is_none()
|| operation.received.is_none_or(|received| received < request.min_out))
{
return Err(differs(details::DIRECT).into());
}
Ok(())
}
async fn enabled_chain(session: &Session, venue: &VenueId) -> Result<EscrowChain> {
let venues = session.client().market().venues().await?;
let chain = venues
.into_iter()
.find(|row| row.id == *venue && row.enabled)
.and_then(|row| row.chain)
.ok_or(unsupported(details::VENUE))?;
if deployment::check_registry(venue, &chain)? != Some(session.escrow_environment()) {
return Err(differs(details::ESCROW).into());
}
Ok(chain)
}
fn check_funds(
session: &Session,
funds: &BridgeFunding,
request: &DirectRequest,
escrow: Address,
) -> Result<()> {
let age = (session.transport().now() - funds.observed_at).num_milliseconds();
let fresh = (-FUNDS_AHEAD_MS..FUNDS_AGE_MS).contains(&age);
if (funds.owner, funds.token, funds.spender) != (session.address(), request.token, escrow)
|| !fresh
|| funds.balance < request.amount
{
return Err(changed(details::DIRECT_FUNDING).into());
}
Ok(())
}
struct Approval {
id: String,
key: String,
}
async fn approve(
session: &Session,
sender: &dyn TransactionSender,
operation: &DirectOperation,
approval: &Approval,
) -> Result<Option<DirectWait>> {
let journal = session.journal();
if let Some(asked) = records::load::<Asked>(journal, &approval.key).await? {
if asked.hash.is_some() {
return Ok(Some(DirectWait::Approval));
}
match status(Some(sender), &approval.id).await {
SendStatus::Sent(hash) => {
let asked = Asked { hash: Some(hash), ..Asked::default() };
records::save(journal, &approval.key, &asked, true).await?;
return Ok(Some(DirectWait::Approval));
}
SendStatus::NotSent => {}
_ => return Ok(Some(DirectWait::Approval)),
}
}
records::save(journal, &approval.key, &Asked::default(), false).await?;
let transaction = Transaction {
id: approval.id.clone(),
chain_id: operation.chain_id,
to: operation.token,
data: approve_data(operation.escrow, operation.amount),
value: U256::ZERO,
};
match sender.send(transaction).await {
Ok(hash) => {
let asked = Asked { hash: Some(hash), ..Asked::default() };
records::save(journal, &approval.key, &asked, true).await?;
Ok(None)
}
Err(SendError::NotSent(error)) => {
tracing::info!(%error, "direct approval not sent");
records::delete(journal, &approval.key, true).await?;
Ok(Some(DirectWait::NotSent))
}
Err(error) => {
tracing::warn!(%error, "direct approval outcome unknown");
Ok(Some(DirectWait::Approval))
}
}
}
fn approve_data(spender: Address, amount: Amount) -> Vec<u8> {
let mut data = APPROVE.to_vec();
data.extend_from_slice(&address_word(spender));
data.extend_from_slice(&amount.get().to_be_bytes::<32>());
data
}
fn address_word(address: Address) -> [u8; 32] {
let mut word = [0; 32];
word[12..].copy_from_slice(address.as_slice());
word
}
fn target(operation: &DirectOperation) -> Address {
match operation.kind {
DirectKind::Withdrawal => gmx::TRANSFER_ROUTER,
_ => operation.escrow,
}
}
fn calldata(operation: &DirectOperation) -> Result<Vec<u8>> {
match operation.kind {
DirectKind::Withdrawal
if operation.venue == VenueId::Gmx && operation.owner == operation.recipient =>
{
Ok(gmx::transfer_out(operation.amount.get()).to_vec())
}
DirectKind::Deposit => {
let mut data = DEPOSIT.to_vec();
data.extend_from_slice(&address_word(operation.recipient));
data.extend_from_slice(&address_word(operation.token));
for value in [operation.amount, operation.min_out, operation.nonce, operation.deadline]
{
data.extend_from_slice(&value.get().to_be_bytes::<32>());
}
Ok(data)
}
_ => Err(changed(details::DIRECT).into()),
}
}
fn in_window(deadline: U256, now: i64) -> bool {
let Ok(now) = u64::try_from(now) else { return false };
let latest = now.saturating_add(DEADLINE_WINDOW_SECONDS.unsigned_abs());
deadline > U256::from(now) && deadline <= U256::from(latest)
}
fn transaction_id(id: Uuid, step: &str) -> String {
format!("lamarge.direct.{id}.{step}")
}
async fn status(sender: Option<&dyn TransactionSender>, id: &str) -> SendStatus {
match sender {
Some(sender) => sender.status(id).await.unwrap_or(SendStatus::Unknown),
None => SendStatus::Unknown,
}
}
#[cfg(test)]
mod tests;