lamarge 0.9.0

Client for the LaMarge API: sign-in, takes, transfers, withdrawals and market making, each request checked before it is signed.
Documentation
//! Funding plan and wallet funding checks.

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

use super::{
    deployment,
    details::{self, changed, differs, stale, unsupported},
};
use crate::{
    deployments,
    error::VerificationError,
    model::{
        FundingPlan, FundingRequestKind, PaymentSetup, Venue, WalletFunding, WithdrawalDestination,
    },
    types::{Amount, EscrowEnvironment, VenueId},
};

/// The caller's terms a transfer's funding plan is checked against.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlanTerms {
    /// The venue paying.
    pub from: VenueId,
    /// The session address.
    pub payer: Address,
    /// The transfer's amount, in `from` base units.
    pub amount_in: Amount,
    /// Paid from the escrow-chain wallet: nothing may leave the venue for it.
    pub wallet_funding: bool,
}

/// Checks a transfer's funding plan (`TransferIntent.funding_plan`, `None` when the server could
/// not plan: its `funding_plan_error` says why) at `now`: what the transfer will ask the payer to
/// sign is at most a permit, a margin withdrawal and the payment, in that order, on `from`'s
/// chain, for `terms`' amount, observed within two minutes.
pub fn check_funding_plan<'a>(
    plan: Option<&'a FundingPlan>,
    terms: &PlanTerms,
    environment: EscrowEnvironment,
    now: DateTime<Utc>,
) -> Result<&'a FundingPlan, VerificationError> {
    let plan = plan.ok_or(changed(details::FUNDING_PLAN))?;
    let chain = deployments::chain(&terms.from).ok_or(unsupported(details::VENUE))?;
    deployments::escrow(chain.id, environment).ok_or(unsupported(details::VENUE))?;
    let (amount, deposit, withdrawal) =
        (plan.amount.get(), plan.deposit.get(), plan.withdrawal_amount.get());
    if plan.venue != terms.from
        || plan.owner != terms.payer
        || plan.amount != terms.amount_in
        || deposit > amount
        || withdrawal > amount
    {
        return Err(changed(details::FUNDING_PLAN));
    }
    let withdraws = !withdrawal.is_zero();
    if terms.wallet_funding && (withdraws || plan.withdrawal_to.is_some()) {
        return Err(differs(details::FUNDING_WITHDRAWAL));
    }
    let age = now - plan.observed_at;
    if age < -Duration::seconds(5) || age >= Duration::seconds(120) {
        return Err(stale(details::FUNDING_OBSERVED_AT));
    }
    let destination = withdraws.then_some(WithdrawalDestination::Signer);
    if plan.withdrawal_to != destination {
        return Err(differs(details::FUNDING_WITHDRAWAL));
    }
    // From GMX the withdrawal is a `transfer_out`, a transaction the payer sends itself.
    let withdrawal_kind = if terms.from == VenueId::Gmx {
        FundingRequestKind::TransferOut
    } else {
        FundingRequestKind::MarginMove
    };
    let kinds: Vec<&FundingRequestKind> =
        plan.requests.iter().map(|request| &request.kind).collect();
    let count = |kind: &FundingRequestKind| kinds.iter().filter(|each| **each == kind).count();
    let permit = plan.payment_setup == PaymentSetup::Required;
    let requests = plan
        .requests
        .iter()
        .all(|request| request.signer == terms.payer && request.chain_id == chain.id)
        && count(&FundingRequestKind::PayTake) == 1
        && kinds.iter().all(|kind| {
            [&FundingRequestKind::Permit, &withdrawal_kind, &FundingRequestKind::PayTake]
                .contains(kind)
                && count(kind) == 1
        })
        && (count(&withdrawal_kind) == 1) == withdraws
        && (count(&FundingRequestKind::Permit) == 1) == permit
        && (!permit || kinds.first() == Some(&&FundingRequestKind::Permit) && !deposit.is_zero());
    if requests { Ok(plan) } else { Err(differs(details::FUNDING_REQUESTS)) }
}

/// Checks that `venue` is enabled with wallet funding in its pinned escrow token
/// (`GET /v1/venues`), in `environment`'s escrow.
pub(crate) fn check_wallet_capability(
    venues: &[Venue],
    venue: &VenueId,
    environment: EscrowEnvironment,
) -> Result<(), VerificationError> {
    let chain = venues
        .iter()
        .find(|row| row.id == *venue && row.enabled)
        .and_then(|row| row.chain.as_ref())
        .ok_or(unsupported(details::VENUE))?;
    match deployment::check_registry(venue, chain)? {
        Some(escrow) if escrow == environment => {}
        Some(_) => return Err(differs(details::ESCROW)),
        // A venue settled inside itself pays from its account.
        None => return Err(unsupported(details::WALLET_FUNDING)),
    }
    let capability = chain.wallet_funding.as_ref().ok_or(unsupported(details::WALLET_FUNDING))?;
    if capability.token == chain.token && capability.decimals == chain.decimals {
        Ok(())
    } else {
        Err(differs(details::WALLET_FUNDING))
    }
}

/// Checks a fresh read of `payer`'s wallet funds on `venue` (`GET /v1/wallets/{venue}`) at `now`
/// against the pins and returns what a new take may spend of them: the pinned chain, escrow and
/// token, the payer's own balances and permission, observed within two minutes.
pub(crate) fn check_wallet_funding(
    funds: &WalletFunding,
    venue: &VenueId,
    payer: Address,
    environment: EscrowEnvironment,
    now: DateTime<Utc>,
) -> Result<U256, VerificationError> {
    let chain = deployments::chain(venue).ok_or(unsupported(details::VENUE))?;
    if funds.venue != *venue
        || funds.chain_id != chain.id
        || Some(funds.escrow) != deployments::escrow(chain.id, environment)
        || funds.token != chain.token
        || funds.decimals != chain.decimals
    {
        return Err(differs(details::WALLET_FUNDS));
    }
    if funds.address != payer || funds.payment_setup.address != payer {
        return Err(changed(details::WALLET_FUNDS));
    }
    let age = now - funds.observed_at;
    if age < -Duration::seconds(15) || age >= Duration::seconds(120) {
        return Err(stale(details::WALLET_FUNDS_OBSERVED_AT));
    }
    if funds.spendable_wallet > funds.wallet || funds.spendable_available > funds.available {
        return Err(differs(details::WALLET_FUNDS));
    }
    funds
        .spendable_wallet
        .get()
        .checked_add(funds.spendable_available.get())
        .ok_or(differs(details::WALLET_FUNDS))
}

#[cfg(test)]
mod tests;