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
//! Maker checks: capital additions (`FundOffer`, margin moves), signed quote sets, closes and
//! created credentials.

use std::collections::HashSet;

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

use super::{
    deadline_bound, deadline_within,
    details::{self, at, changed, differs, stale, unsupported},
    differs_unless, escrow, signed, withdrawal,
};
use crate::{
    deployments,
    error::VerificationError,
    model::{
        CredentialCreated, CredentialScope, FundingSource, MakerPreparation, MakerPreparationState,
        Order, ToSign, ToSignKind,
    },
    protocol::{
        eip712::{self, CloseOrders, FundOffer, QuoteSet},
        signing::Verified,
    },
    types::{Amount, ClientId, EscrowEnvironment, OrderId, QuoteIdentityId, VenueId},
};

/// The longest a maker preparation, funding or close may stay signable.
const MAKER_SECONDS: i64 = 3600;
/// The highest quote sequence, a quote set's or a funding's floor: JavaScript's largest exact
/// integer, as the server caps it.
pub(super) const MAX_SEQUENCE: u64 = (1 << 53) - 1;

/// The caller's capital addition a maker preparation is checked against.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CapitalRequest {
    /// The pool's venue.
    pub venue: VenueId,
    /// Capital to add, in `venue` base units.
    pub amount: Amount,
    /// The request's own id.
    pub client_request_id: ClientId,
    /// Where the capital comes from.
    pub funding_source: FundingSource,
}

/// Who a maker preparation may name: the linked owner, the delegated identity and its quote
/// signer, the deployment's operator, and the identity's existing pool on the venue, if any.
#[derive(Debug, Clone, Copy)]
pub struct MakerAuthority<'a> {
    /// The linked owner, who funds.
    pub owner: Address,
    /// The delegated identity's quote signer.
    pub quote_signer: Address,
    /// The delegated identity.
    pub quote_identity_id: QuoteIdentityId,
    /// The deployment's operator.
    pub operator: Address,
    /// The identity's pool on the venue, as last read, if any.
    pub existing: Option<&'a Order>,
}

/// Checks a maker preparation (`POST /v1/maker/prepare`) for a delegated quote identity at `now`
/// and returns its payloads, in `to_sign` order: the `FundOffer` of all the capital asked, its
/// deposit only the part the pool's available balance does not cover, from the asked source, and
/// for venue funding one margin move of that deposit. A delegated identity's quotes are never
/// re-signed here, so any `quote_set` request is refused.
pub fn check_maker_intent(
    prepared: &MakerPreparation,
    request: &CapitalRequest,
    authority: &MakerAuthority<'_>,
    environment: EscrowEnvironment,
    now: DateTime<Utc>,
) -> Result<Vec<Verified>, VerificationError> {
    if deployments::is_venue_settled(&request.venue) {
        return Err(unsupported(details::VENUE));
    }
    let (order, intent) = (&prepared.order, &prepared.intent);
    let identity = authority.quote_identity_id;
    differs_unless([
        (prepared.state == MakerPreparationState::Preparing, details::STATE),
        (prepared.client_request_id == request.client_request_id, details::CLIENT_REQUEST_ID),
        (prepared.venue == request.venue && order.venue == request.venue, details::VENUE),
        (order.owner_address == authority.owner, details::ORDER_OWNER_ADDRESS),
        (order.quote_signer == authority.quote_signer, details::ORDER_QUOTE_SIGNER),
        (order.quote_identity_id == identity, details::ORDER_QUOTE_IDENTITY_ID),
        (intent.amount == request.amount, details::INTENT_AMOUNT),
        (intent.quote_identity_id == identity, details::INTENT_QUOTE_IDENTITY_ID),
        (intent.funding_source == request.funding_source, details::INTENT_FUNDING_SOURCE),
        (prepared.expected_revision == order.revision, details::EXPECTED_REVISION),
    ])?;
    let expires = U256::try_from(prepared.expires_at.timestamp()).unwrap_or(U256::ZERO);
    if !deadline_within(expires, now.timestamp(), MAKER_SECONDS) {
        return Err(stale(details::EXPIRES_AT));
    }
    let available = check_existing(order, request, authority)?;
    let deposit = check_deposit(prepared, request, available)?;
    let kinds: Vec<&ToSignKind> = prepared.to_sign.iter().map(|item| &item.kind).collect();
    let unique = kinds.iter().collect::<HashSet<_>>().len() == kinds.len();
    let moves = !deposit.venue.is_zero();
    let allowed = kinds.iter().all(|kind| match kind {
        ToSignKind::Fund => true,
        ToSignKind::MarginMove => moves,
        _ => false,
    });
    if !unique
        || !allowed
        || !kinds.contains(&&ToSignKind::Fund)
        || kinds.contains(&&ToSignKind::MarginMove) != moves
    {
        return Err(differs(details::TO_SIGN));
    }
    if prepared.sequence.is_some() {
        return Err(differs(details::SEQUENCE));
    }
    prepared
        .to_sign
        .iter()
        .map(|item| match item.kind {
            ToSignKind::MarginMove => {
                check_margin_move(item, &request.venue, deposit.venue, authority.owner, now)
            }
            _ => check_fund(item, order, request, authority, deposit.total, environment, now),
        })
        .collect()
}

/// What the pool had available as last read: an existing pool is the identity's and unchanged
/// since; a new one has no quotes or capital yet.
fn check_existing(
    order: &Order,
    request: &CapitalRequest,
    authority: &MakerAuthority<'_>,
) -> Result<U256, VerificationError> {
    let Some(existing) = authority.existing else {
        let new = order.last_sequence == 0 && order.available_to_quote.get().is_zero();
        return if new { Ok(U256::ZERO) } else { Err(differs(details::ORDER)) };
    };
    if order.id != existing.id {
        return Err(differs(details::ORDER_ID));
    }
    if existing.venue != request.venue
        || existing.owner_address != authority.owner
        || existing.quote_signer != authority.quote_signer
        || existing.quote_identity_id != authority.quote_identity_id
    {
        return Err(differs(details::EXISTING_ORDER));
    }
    if order.last_sequence != existing.last_sequence
        || order.available_to_quote != existing.available_to_quote
        || order.revision < existing.revision
    {
        return Err(changed(details::MAKER_CAPITAL));
    }
    Ok(existing.available_to_quote.get())
}

/// A capital addition's deposit, and what of it leaves the venue's margin.
struct Deposit {
    total: U256,
    venue: U256,
}

/// The capital asked is the idle balance plus the deposit, the deposit is only what the pool's
/// spare available balance does not cover, and it comes from the asked source alone.
fn check_deposit(
    prepared: &MakerPreparation,
    request: &CapitalRequest,
    available: U256,
) -> Result<Deposit, VerificationError> {
    let funding = &prepared.funding;
    let amount = request.amount.get();
    let (idle, wallet, venue, existing) = (
        funding.idle_amount.get(),
        funding.wallet_amount.get(),
        funding.venue_amount.get(),
        funding.existing_available.get(),
    );
    let total = wallet.checked_add(venue).ok_or(differs(details::FUNDING_DEPOSIT))?;
    if amount.is_zero() {
        return Err(differs(details::AMOUNT));
    }
    if existing < available {
        return Err(differs(details::FUNDING_EXISTING_AVAILABLE));
    }
    if idle.checked_add(total) != Some(amount) {
        return Err(differs(details::FUNDING_IDLE_AMOUNT));
    }
    match request.funding_source {
        FundingSource::Venue if !wallet.is_zero() => {
            return Err(differs(details::FUNDING_WALLET_AMOUNT));
        }
        FundingSource::Wallet if !venue.is_zero() => {
            return Err(differs(details::FUNDING_VENUE_AMOUNT));
        }
        FundingSource::Venue | FundingSource::Wallet => {}
        FundingSource::Unknown(_) => return Err(unsupported(details::INTENT_FUNDING_SOURCE)),
    }
    if total != amount.saturating_sub(existing - available) {
        return Err(differs(details::FUNDING_DEPOSIT));
    }
    Ok(Deposit { total, venue })
}

/// A margin move of the whole venue deposit, rounded up to whole millionths (the wallet keeps
/// the rest), by the owner to the owner.
fn check_margin_move(
    item: &ToSign,
    venue: &VenueId,
    amount: U256,
    owner: Address,
    now: DateTime<Utc>,
) -> Result<Verified, VerificationError> {
    let moved =
        deployments::venue_units(amount, venue).ok_or(differs(details::MARGIN_MOVE_AMOUNT))?;
    if item.signer != owner {
        return Err(differs(details::MARGIN_MOVE_SIGNER));
    }
    if withdrawal::margin_withdrawal_cost(&item.typed_data, venue)?.get() != moved {
        return Err(differs(details::MARGIN_MOVE_AMOUNT));
    }
    withdrawal::check_margin_withdrawal(
        &item.typed_data,
        venue,
        owner,
        owner,
        Amount::new(moved),
        now,
        None,
    )
}

/// The owner's funding of `order` with all the capital asked, `deposit`, the identity's quote
/// signer and the operator, its quote floor above the order's last sequence, within the hour.
fn check_fund(
    item: &ToSign,
    order: &Order,
    request: &CapitalRequest,
    authority: &MakerAuthority<'_>,
    deposit: U256,
    environment: EscrowEnvironment,
    now: DateTime<Utc>,
) -> Result<Verified, VerificationError> {
    let owner = authority.owner;
    let (parsed, domain) =
        escrow::check_escrow_typed::<FundOffer>(&item.typed_data, &order.venue, environment)?;
    let fund = &parsed.message;
    let floor = fund.minQuoteSequence;
    differs_unless([
        (item.signer == owner, details::FUND_SIGNER),
        (fund.owner == owner, details::FUND_OWNER),
        (fund.offerId == *order.id.as_b256(), details::FUND_OFFER_ID),
        (fund.amount == request.amount.get(), details::FUND_AMOUNT),
        (fund.deposit == deposit, details::FUND_DEPOSIT),
        (fund.quoteSigner == authority.quote_signer, details::FUND_QUOTE_SIGNER),
        (fund.operator == authority.operator, details::FUND_OPERATOR),
        (floor > order.last_sequence && floor <= MAX_SEQUENCE, details::FUND_MIN_QUOTE_SEQUENCE),
    ])?;
    if !deadline_within(fund.deadline, now.timestamp(), MAKER_SECONDS) {
        return Err(stale(details::DEADLINE));
    }
    let not_after = Some(deadline_bound(fund.deadline));
    Verified::typed(eip712::typed(fund, domain), parsed.digest, owner, not_after)
}

/// The terms of one quote, as the maker set them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct QuoteTerms {
    /// The venue the taker pays on.
    pub venue: VenueId,
    /// Who the taker pays on `venue`.
    pub recipient: Address,
    /// What the pool supplies at most, in its venue's base units.
    pub supply: U256,
    /// What the pool receives for all its supply, in `venue` base units.
    pub receive: U256,
    /// The smallest fill, in the pool's venue base units.
    pub min_fill: U256,
}

/// Checks a quote set to sign for `pool` (its id, venue, owner and quote signer): exactly the
/// `requested` quotes, in order (each position is the index a fill names), at `sequence`,
/// settling by `expires_at`, in the pool's pinned signing domain; signable before `valid_until`,
/// its last admission time (Unix seconds).
pub fn check_signed_quote(
    item: &ToSign,
    pool: &Order,
    requested: &[QuoteTerms],
    sequence: u64,
    valid_until: u64,
    expires_at: u64,
    environment: EscrowEnvironment,
) -> Result<Verified, VerificationError> {
    let (parsed, domain) =
        escrow::check_escrow_typed::<QuoteSet>(&item.typed_data, &pool.venue, environment)?;
    let set = &parsed.message;
    differs_unless([
        (item.kind == ToSignKind::QuoteSet, details::KIND),
        (item.signer == pool.quote_signer, details::TO_SIGN_SIGNER),
        (set.owner == pool.owner_address, details::OWNER),
        (set.offerId == *pool.id.as_b256(), details::OFFER_ID),
        (set.sequence == sequence, details::SEQUENCE),
        (set.expiresAt == expires_at, details::EXPIRES_AT),
        (!requested.is_empty() && set.quotes.len() == requested.len(), details::QUOTES),
    ])?;
    for (index, (quote, expected)) in set.quotes.iter().zip(requested).enumerate() {
        let chain = deployments::chain(&expected.venue);
        let venue = quote.venue.parse::<VenueId>().ok();
        differs_unless([
            (
                chain.is_some()
                    && venue.as_ref() == Some(&expected.venue)
                    && expected.venue != pool.venue,
                details::QUOTES_VENUE,
            ),
            (
                chain.is_some_and(|chain| quote.chainId == U256::from(chain.id)),
                details::QUOTES_CHAIN_ID,
            ),
            (chain.is_some_and(|chain| quote.token == chain.token), details::QUOTES_TOKEN),
            (quote.recipient == expected.recipient, details::QUOTES_RECIPIENT),
            (quote.supply == expected.supply && !quote.supply.is_zero(), details::QUOTES_SUPPLY),
            (
                quote.receive == expected.receive && !quote.receive.is_zero(),
                details::QUOTES_RECEIVE,
            ),
            (
                quote.minFill == expected.min_fill && quote.minFill <= quote.supply,
                details::QUOTES_MIN_FILL,
            ),
        ])
        .map_err(|error| at(error, index))?;
    }
    let not_after = Some(signed(valid_until).saturating_sub(1));
    Verified::typed(eip712::typed(set, domain), parsed.digest, pool.quote_signer, not_after)
}

/// Checks a close (`POST /v1/closes`) of orders among `ids` by `master` at `now`: one
/// `CloseOrders` in the HyperEVM escrow's domain (LaMarge's operator authorization), by and for
/// the master, of distinct asked orders, within the hour.
pub fn check_close_orders(
    items: &[ToSign],
    ids: &[OrderId],
    master: Address,
    environment: EscrowEnvironment,
    now: DateTime<Utc>,
) -> Result<Verified, VerificationError> {
    let [item] = items else {
        return Err(differs(details::TO_SIGN));
    };
    let (parsed, domain) = escrow::check_escrow_typed::<CloseOrders>(
        &item.typed_data,
        &VenueId::Hyperliquid,
        environment,
    )?;
    let close = &parsed.message;
    let distinct = close.orders.iter().collect::<HashSet<_>>().len() == close.orders.len();
    let asked = close.orders.iter().all(|order| ids.iter().any(|id| id.as_b256() == order));
    differs_unless([
        (item.kind == ToSignKind::CloseOrders, details::KIND),
        (item.signer == master, details::TO_SIGN_SIGNER),
        (close.account == master, details::ACCOUNT),
        (!close.orders.is_empty() && distinct && asked, details::ORDERS),
    ])?;
    if !deadline_within(close.deadline, now.timestamp(), MAKER_SECONDS) {
        return Err(stale(details::DEADLINE));
    }
    let not_after = Some(deadline_bound(close.deadline));
    Verified::typed(eip712::typed(close, domain), parsed.digest, master, not_after)
}

/// Checks a created credential (`POST /v1/credentials`) echoes the quote signer and scopes asked.
pub(crate) fn check_created_credential(
    created: &CredentialCreated,
    quote_signer: Address,
    scopes: &[CredentialScope],
) -> Result<(), VerificationError> {
    if created.quote_signer != quote_signer {
        return Err(differs(details::CREDENTIAL_QUOTE_SIGNER));
    }
    if created.scopes != scopes {
        return Err(differs(details::CREDENTIAL_SCOPES));
    }
    Ok(())
}

#[cfg(test)]
mod tests;