lamarge 0.7.0

Client for the LaMarge API: sign-in, takes, transfers, withdrawals and market making, each request checked before it is signed.
Documentation
//! What a linked account's balance row (`GET /v1/balances`) allows: what a take pays without
//! moving margin, what the relayer sweeps, what a withdrawal keeps back.

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

use crate::{
    model::Balance,
    types::{Amount, VenueId},
};

/// How long a balance read stays fresh, in milliseconds: two minutes.
pub const FRESH_MS: i64 = 120_000;

/// Whether a read `at` is under [`FRESH_MS`] old at `now`; a missing time is stale.
pub fn fresh(at: Option<DateTime<Utc>>, now: DateTime<Utc>) -> bool {
    at.is_some_and(|at| now - at < TimeDelta::milliseconds(FRESH_MS))
}

/// What the deposit address holds that the relayer sweeps without a withdrawal to it: at least
/// one whole unit of the venue's token, dust otherwise.
pub fn sweepable(balance: &Balance) -> Amount {
    let held = balance.deposit_balance.unwrap_or(Amount::ZERO);
    let minimum =
        balance.venue.decimals().map(|decimals| U256::from(10u8).pow(U256::from(decimals)));
    if minimum.is_some_and(|minimum| held.get() >= minimum) { held } else { Amount::ZERO }
}

/// What a take pays without moving margin, from a fresh, successful escrow-chain read: the
/// linked address's balance, whose funds the take deposits, and the escrow available balance.
/// `None` when unknown: any chain error, even an empty text, makes the read unsuccessful.
pub fn prefunded(balance: &Balance, now: DateTime<Utc>) -> Option<Amount> {
    if balance.chain_error.is_some() || !fresh(balance.chain_read_at, now) {
        return None;
    }
    let escrow = balance.escrow_balance.unwrap_or(Amount::ZERO).get();
    balance.chain_balance?.get().checked_add(escrow).map(Amount::new)
}

/// What a withdrawal keeps back of the margin: the venue's fee, and on Hyperliquid the gas
/// reserve. `None` when either is unknown.
pub fn withdrawal_budget(balance: &Balance) -> Option<Amount> {
    let fee = balance.withdrawal_fee?;
    let reserve = match (&balance.venue, balance.withdrawal_reserve) {
        (VenueId::Hyperliquid, None) => return None,
        (_, reserve) => reserve.unwrap_or(Amount::ZERO),
    };
    fee.get().checked_add(reserve.get()).map(Amount::new)
}

#[cfg(test)]
mod tests;