lamarge 0.8.0

Client for the LaMarge API: sign-in, takes, transfers, withdrawals and market making, each request checked before it is signed.
Documentation
//! What a direct transaction does, read from its calldata alone, for a signer that holds the key
//! apart (a browser wallet, an isolated key service) and sends only these calls.

use alloy_primitives::{Address, U256};
use chrono::{DateTime, Utc};

use super::{DEPOSIT, in_window};
use crate::{
    Result,
    deployments::{self, GMX, HYPERLIQUID, POLYMARKET},
    error::VerificationError,
    flows::conversion::{APPROVE, CONVERT, LEAST_CONVERTED, POLYGON_USDC, conversion_minimum},
    protocol::{
        checks::details::{self, deployment, differs, stale, unsupported},
        gmx,
    },
    types::{Amount, VenueId},
};

/// A direct transaction's call.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DirectStep {
    /// `approve(escrow, amount)` of the venue's token, or Polygon's native USDC.
    Approve,
    /// The escrow's `directDeposit`.
    Deposit,
    /// GMX's `transferOut` to its sender.
    Withdrawal,
    /// The Polygon escrow's conversion of native USDC into pUSD.
    Convert,
}

/// What a direct transaction does.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct DirectInspection {
    /// The call.
    pub step: DirectStep,
    /// The venue whose chain it is sent on.
    pub venue: VenueId,
    /// The token it spends or approves.
    pub token: Address,
    /// Who is credited: the deposit's recipient, else the owner.
    pub recipient: Address,
    /// In the token's base units.
    pub amount: Amount,
    /// The least received; zero for an `approve`.
    pub minimum: Amount,
}

/// Checks a direct operation's input token and minimum, as both the sender and
/// [`inspect_direct_transaction`] do: the venue's own token moves whole (`minimum == amount`); a
/// deposit into Polymarket may instead spend Polygon's native USDC, at least one cent, for at
/// least its [`conversion_minimum`](crate::flows::conversion_minimum) of pUSD.
///
/// # Errors
///
/// `Verification(Unsupported)` for a venue this release does not pin or a token neither allows;
/// `Verification(Differs)` for a zero amount or minimum, or a minimum under its floor.
pub fn check_direct_amounts(
    venue: &VenueId,
    token: Address,
    amount: Amount,
    minimum: Amount,
    deposit: bool,
) -> Result<()> {
    amounts(venue, token, amount, minimum, deposit).map_err(Into::into)
}

pub(super) fn amounts(
    venue: &VenueId,
    token: Address,
    amount: Amount,
    minimum: Amount,
    deposit: bool,
) -> std::result::Result<(), VerificationError> {
    let chain = deployments::chain(venue).ok_or(unsupported(details::VENUE))?;
    if amount.get().is_zero() || minimum.get().is_zero() {
        return Err(differs(details::DIRECT_AMOUNT));
    }
    if token == chain.token {
        return if amount == minimum { Ok(()) } else { Err(differs(details::DIRECT_AMOUNT)) };
    }
    if !deposit || *venue != VenueId::Polymarket || Some(token) != chain.wallet_token {
        return Err(unsupported(details::DIRECT_TOKEN));
    }
    let floor = conversion_minimum(amount).ok_or(differs(details::DIRECT_AMOUNT))?;
    if amount.get() >= U256::from(LEAST_CONVERTED) && minimum >= floor {
        Ok(())
    } else {
        Err(differs(details::DIRECT_AMOUNT))
    }
}

/// Reads the call of `data` to `to` on chain `chain_id`, sent by `owner`, and accepts only the
/// direct calls the SDK builds: an `approve` of a pinned escrow, an escrow deposit crediting
/// `recipient` (the request's: calldata cannot show an address is a linked account; pass `owner`
/// for its own account), Polygon's conversion, or GMX's `transferOut`, on HyperEVM, Polygon or
/// Arbitrum. A deposit's or conversion's deadline must be within the server's window from `now`.
/// None of them carries a native value, which this check does not see: a caller must refuse a
/// transaction with a non-zero value itself.
///
/// A host's [`TransactionSender`](crate::TransactionSender) can check each
/// [`Transaction`](crate::Transaction) it is asked for with its `chain_id`, `to` and `data`.
///
/// # Errors
///
/// `Verification(..)` for any other chain, contract, call or encoding, an escrow this release
/// does not pin, another recipient, amounts [`check_direct_amounts`] refuses, or a deadline out
/// of its window.
pub fn inspect_direct_transaction(
    chain_id: u64,
    to: Address,
    data: &[u8],
    owner: Address,
    recipient: Address,
    now: DateTime<Utc>,
) -> Result<DirectInspection> {
    inspect(chain_id, to, data, owner, recipient, now.timestamp()).map_err(Into::into)
}

fn inspect(
    chain_id: u64,
    to: Address,
    data: &[u8],
    owner: Address,
    recipient: Address,
    now: i64,
) -> std::result::Result<DirectInspection, VerificationError> {
    let (venue, chain) = [
        (VenueId::Hyperliquid, &HYPERLIQUID),
        (VenueId::Polymarket, &POLYMARKET),
        (VenueId::Gmx, &GMX),
    ]
    .into_iter()
    .find(|(_, chain)| chain.id == chain_id)
    .ok_or(unsupported(details::VENUE))?;
    let pinned = |escrow: Address| {
        deployments::escrow_environment(chain.id, escrow)
            .map(drop)
            .ok_or(deployment(details::ESCROW))
    };
    let token_allowed = to == chain.token || (venue == VenueId::Polymarket && to == POLYGON_USDC);
    if data.starts_with(&APPROVE) && data.len() == 4 + 2 * 32 && token_allowed {
        pinned(read_address(data, 0)?)?;
        let amount = read_amount(data, 1);
        if amount.get().is_zero() {
            return Err(differs(details::DIRECT_AMOUNT));
        }
        let (step, minimum) = (DirectStep::Approve, Amount::ZERO);
        return Ok(DirectInspection { step, venue, token: to, recipient: owner, amount, minimum });
    }
    if data.starts_with(&DEPOSIT) && data.len() == 4 + 6 * 32 {
        pinned(to)?;
        let credited = read_address(data, 0)?;
        let token = read_address(data, 1)?;
        let (amount, minimum, deadline) =
            (read_amount(data, 2), read_amount(data, 3), word(data, 5));
        if credited != recipient {
            return Err(differs(details::DIRECT_RECIPIENT));
        }
        amounts(&venue, token, amount, minimum, true)?;
        if !in_window(deadline, now) {
            return Err(stale(details::DEADLINE));
        }
        let step = DirectStep::Deposit;
        return Ok(DirectInspection { step, venue, token, recipient: credited, amount, minimum });
    }
    if venue == VenueId::Polymarket && data.starts_with(&CONVERT) && data.len() == 4 + 4 * 32 {
        pinned(to)?;
        let (amount, minimum, deadline) =
            (read_amount(data, 0), read_amount(data, 1), word(data, 3));
        amounts(&venue, POLYGON_USDC, amount, minimum, true)?;
        if !in_window(deadline, now) {
            return Err(stale(details::DEADLINE));
        }
        let (step, token) = (DirectStep::Convert, POLYGON_USDC);
        return Ok(DirectInspection { step, venue, token, recipient: owner, amount, minimum });
    }
    if venue == VenueId::Gmx && to == gmx::TRANSFER_ROUTER && data.len() == 4 + 13 * 32 {
        let amount = read_amount(data, 2);
        if amount.get().is_zero() || data != gmx::transfer_out(amount.get()).to_vec().as_slice() {
            return Err(differs(details::DIRECT_TRANSACTION));
        }
        let (step, token) = (DirectStep::Withdrawal, chain.token);
        return Ok(DirectInspection {
            step,
            venue,
            token,
            recipient: owner,
            amount,
            minimum: amount,
        });
    }
    Err(unsupported(details::DIRECT_TRANSACTION))
}

/// The `index`-th argument word after the selector; the callers checked the length.
fn word(data: &[u8], index: usize) -> U256 {
    let start = 4 + index * 32;
    data.get(start..start + 32).map_or(U256::ZERO, U256::from_be_slice)
}

fn read_amount(data: &[u8], index: usize) -> Amount {
    Amount::new(word(data, index))
}

/// An address argument: its word's twelve leading bytes are zero.
fn read_address(data: &[u8], index: usize) -> std::result::Result<Address, VerificationError> {
    let start = 4 + index * 32;
    match data.get(start..start + 32) {
        Some(word) if word[..12].iter().all(|byte| *byte == 0) => {
            Ok(Address::from_slice(&word[12..]))
        }
        _ => Err(differs(details::DIRECT_TRANSACTION)),
    }
}