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
//! Pinned deployments: chains, tokens, escrows and signing domains per environment.
//!
//! Copied from `sdk-ts/src/protocol/{protocol,deployments}.ts`; `tests/vectors/pins.json`, generated
//! from the TypeScript objects, must equal these tables (unit test below). A new deployment
//! changes both SDKs together. The public items are re-exported by [`crate::protocol`].

use alloy_primitives::{Address, U256, address};

use crate::types::{EscrowEnvironment, VenueId};

/// An EIP-2612 permit domain's name and version.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct PermitDomain {
    /// The domain's `name`.
    pub name: &'static str,
    /// The domain's `version`.
    pub version: &'static str,
}

/// A venue's settlement chain: the escrow chain of an escrow venue, the signing chain of a venue
/// settled inside itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Chain {
    /// The chain id (Lighter: its L2 chain id).
    pub id: u64,
    /// The settlement token (USDC, pUSD, USDT).
    pub token: Address,
    /// The token's decimals.
    pub decimals: u8,
    /// The token's permit domain, if it has one.
    pub permit: Option<PermitDomain>,
    /// What a wallet delivery pays on this chain, of `decimals` too; none on a venue settled
    /// inside itself.
    pub wallet_token: Option<Address>,
}

impl Chain {
    /// One millionth of the token: venues move six decimals at most.
    pub(crate) fn step(&self) -> U256 {
        U256::from(10u8).pow(U256::from(self.decimals.saturating_sub(6)))
    }
}

/// HyperEVM and USDC.
pub(crate) const HYPERLIQUID: Chain = Chain {
    id: 999,
    token: address!("b88339cb7199b77e23db6e890353e22632ba630f"),
    decimals: 6,
    permit: Some(PermitDomain { name: "USDC", version: "2" }),
    wallet_token: Some(address!("b88339cb7199b77e23db6e890353e22632ba630f")),
};
/// Polygon and pUSD.
pub(crate) const POLYMARKET: Chain = Chain {
    id: 137,
    token: address!("c011a7e12a19f7b1f670d46f03b03f3342e82dfb"),
    decimals: 6,
    permit: Some(PermitDomain { name: "Polymarket USD", version: "1" }),
    // Native USDC, converted from pUSD.
    wallet_token: Some(address!("3c499c542cef5e3811e1192ce70d8cc03d5c3359")),
};
/// Arbitrum and USDC.
pub(crate) const GMX: Chain = Chain {
    id: 42161,
    token: address!("af88d065e77c8cc2239327c5edb3a432268e5831"),
    decimals: 6,
    permit: Some(PermitDomain { name: "USD Coin", version: "2" }),
    wallet_token: Some(address!("af88d065e77c8cc2239327c5edb3a432268e5831")),
};
/// Lighter's L2 chain id and its USDC on Ethereum.
pub(crate) const LIGHTER: Chain = Chain {
    id: 304,
    token: address!("a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"),
    decimals: 6,
    permit: None,
    wallet_token: None,
};
/// BSC and USDT.
pub(crate) const ASTER: Chain = Chain {
    id: 56,
    token: address!("55d398326f99059ff775485246999027b3197955"),
    decimals: 18,
    permit: None,
    wallet_token: None,
};

/// Each venue's pinned chain, token, decimals and permit domain. A venue the API enables but
/// that is not pinned here is not traded.
pub const CHAINS: [(VenueId, Chain); 5] = [
    (VenueId::Hyperliquid, HYPERLIQUID),
    (VenueId::Polymarket, POLYMARKET),
    (VenueId::Aster, ASTER),
    (VenueId::Lighter, LIGHTER),
    (VenueId::Gmx, GMX),
];

/// `venue`'s pinned chain; `None` for a venue this SDK does not trade.
pub(crate) fn chain(venue: &VenueId) -> Option<&'static Chain> {
    match venue {
        VenueId::Hyperliquid => Some(&HYPERLIQUID),
        VenueId::Polymarket => Some(&POLYMARKET),
        VenueId::Gmx => Some(&GMX),
        VenueId::Lighter => Some(&LIGHTER),
        VenueId::Aster => Some(&ASTER),
        VenueId::Unknown(_) => None,
    }
}

/// Whether `venue` settles inside itself (no escrow): Lighter and Aster.
pub fn is_venue_settled(venue: &VenueId) -> bool {
    matches!(venue, VenueId::Lighter | VenueId::Aster)
}

/// A reviewed escrow proxy (v5 UUPS), never an implementation or an address the API supplies.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Escrow {
    /// The escrow's chain.
    pub chain_id: u64,
    /// The proxy's address.
    pub address: Address,
    /// The environment it serves.
    pub environment: EscrowEnvironment,
}

/// The active escrows, one per environment and escrow chain. Retired proxies are not pinned:
/// nothing new is signed for them.
pub const ESCROWS: [Escrow; 6] = [
    Escrow { chain_id: 999, address: ESCROW, environment: EscrowEnvironment::Production },
    Escrow { chain_id: 137, address: ESCROW, environment: EscrowEnvironment::Production },
    Escrow {
        chain_id: 42161,
        address: address!("7b0c3eb38153614452a56bc9295d1bd084a9190a"),
        environment: EscrowEnvironment::Production,
    },
    Escrow {
        chain_id: 999,
        address: address!("948e65c40442d935d4ee990bdbd01bdd825c4873"),
        environment: EscrowEnvironment::Development,
    },
    Escrow {
        chain_id: 137,
        address: address!("a3fca394739ec4b984e908bd7a3c3b72d0ed77d1"),
        environment: EscrowEnvironment::Development,
    },
    Escrow {
        chain_id: 42161,
        address: address!("66e4c25d7e92c3e2765b021a748e740f775ac112"),
        environment: EscrowEnvironment::Development,
    },
];

/// Production's escrow proxy, the same address on HyperEVM and Polygon. A deployment's escrows
/// are those [`ESCROWS`] pins for its environment.
pub const ESCROW: Address = address!("3100b7b49c0f9631c6af25877b5a4e13a47afad6");

/// The pinned escrow of `environment` on `chain_id`.
pub(crate) fn escrow(chain_id: u64, environment: EscrowEnvironment) -> Option<Address> {
    ESCROWS
        .iter()
        .find(|escrow| escrow.chain_id == chain_id && escrow.environment == environment)
        .map(|escrow| escrow.address)
}

/// The environment whose pinned escrow on `chain_id` is `address`.
pub(crate) fn escrow_environment(chain_id: u64, address: Address) -> Option<EscrowEnvironment> {
    ESCROWS
        .iter()
        .find(|escrow| escrow.chain_id == chain_id && escrow.address == address)
        .map(|escrow| escrow.environment)
}

/// The signing domain of a venue settled inside itself.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct VenueDomain {
    /// The venue.
    pub venue: VenueId,
    /// Its signing chain id.
    pub chain_id: u64,
    /// The domain's contract.
    pub address: Address,
}

/// Signing domains of venues without escrow: Lighter's L2 chain id and zkLighter contract, BSC
/// and Aster's vault. Quote sets of inventory held there are signed in them; nothing is ever sent
/// to them.
pub const VENUE_DOMAINS: [VenueDomain; 2] = [
    VenueDomain {
        venue: VenueId::Lighter,
        chain_id: LIGHTER.id,
        address: address!("3b4d794a66304f130a4db8f2551b0070dfcf5ca7"),
    },
    VenueDomain {
        venue: VenueId::Aster,
        chain_id: ASTER.id,
        address: address!("128463a60784c4d3f46c23af3f65ed859ba87974"),
    },
];

/// The contract a venue settled inside itself signs quote sets for, on its own chain, and nothing
/// is ever sent to: Lighter's zkLighter contract, Aster's vault.
pub(crate) fn venue_contract(venue: &VenueId) -> Option<Address> {
    VENUE_DOMAINS.iter().find(|domain| domain.venue == *venue).map(|domain| domain.address)
}

/// The contract `venue`'s escrow requests name: its [`venue_contract`], else `environment`'s
/// escrow on its chain.
pub(crate) fn contract(venue: &VenueId, environment: EscrowEnvironment) -> Option<Address> {
    venue_contract(venue).or_else(|| escrow(chain(venue)?.id, environment))
}

/// What an environment registers on venues: registering another environment's slot replaces it,
/// so environments use distinct Aster agent names and Lighter API key indexes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Slots {
    /// The name of LaMarge's Aster agent.
    pub aster_agent_name: &'static str,
    /// The index of LaMarge's Lighter API key.
    pub lighter_key_index: u8,
}

/// `environment`'s Aster agent name and Lighter API key index.
pub(crate) const fn slots(environment: EscrowEnvironment) -> Slots {
    match environment {
        EscrowEnvironment::Production => {
            Slots { aster_agent_name: "LaMarge", lighter_key_index: 254 }
        }
        EscrowEnvironment::Development => {
            Slots { aster_agent_name: "LaMargeDev", lighter_key_index: 253 }
        }
    }
}

/// Each environment's Aster agent name and Lighter API key index.
pub const ENVIRONMENT_SLOTS: [(EscrowEnvironment, Slots); 2] = [
    (EscrowEnvironment::Production, slots(EscrowEnvironment::Production)),
    (EscrowEnvironment::Development, slots(EscrowEnvironment::Development)),
];

/// Seconds a quote set outlasts its `valid_until` (`FILL_MAKER_TIMEOUT`), and the latest `t1`.
pub const MAKER_TIMEOUT_SECONDS: u64 = 3600;
/// The latest a take's payment refunds, `t2`: the escrow's `MAX_LOCK_DURATION`.
pub const TAKER_TIMEOUT_SECONDS: u64 = 86_400;
/// The most seconds to a route's second take's `pay_by` when signed at once.
pub const ROUTE_PAY_WINDOW_SECONDS: u64 = 210;
/// A take signed at once with its withdrawal is accepted until this long before its `pay_by`.
pub const AT_ONCE_SEND_MARGIN_SECONDS: u64 = 30;
/// Left before that cutoff for each request of a take signed at once.
pub const AT_ONCE_SIGNING_SECONDS: u64 = 30;
/// The least share of a Polygon wallet delivery's pUSD its recipient receives in native USDC.
pub const WALLET_SWAP_MIN_BPS: u16 = 9_995;
/// The allowance a permit grants, once.
pub const UNLIMITED_ALLOWANCE: U256 = U256::MAX;
/// The most Lighter charges a taker's account on top of a transfer: 1 USDC.
pub const LIGHTER_MAX_TAKER_FEE: U256 = U256::from_limbs([1_000_000, 0, 0, 0]);
/// USDC on `HyperCore`, as `SendAsset` names it.
pub(crate) const HYPERLIQUID_USDC: &str = "USDC:0x6d1e7cde53ba9467b783cb7c530ce054";
/// USDC's `HyperCore` system address: a `SendAsset` there withdraws to the sender's HyperEVM
/// address.
pub(crate) const HYPERLIQUID_BRIDGE: Address = address!("2000000000000000000000000000000000000000");
/// The contract of Polymarket's withdrawal signing domain.
pub(crate) const POLYMARKET_WITHDRAW_CONTRACT: Address =
    address!("dca4af75705dbb50f62437045aff9921947917d2");

/// `value` rounded up to whole millionths of `venue`'s token: what the venue moves for it.
/// `None` for an unknown venue or above `2^256 - 1`.
pub fn venue_units(value: U256, venue: &VenueId) -> Option<U256> {
    let step = chain(venue)?.step();
    let remainder = value % step;
    if remainder.is_zero() { Some(value) } else { value.checked_add(step - remainder) }
}

/// One millionth of `venue`'s token, in base units: venues carry six decimals at most. `None`
/// for an unknown venue.
pub fn venue_step(venue: &VenueId) -> Option<U256> {
    chain(venue).map(Chain::step)
}

/// A venue's decimal token amount (`"12.5"`, six decimals at most) in base units of a token with
/// `decimals`, exactly. `None` for any other text.
pub fn decimal_units(text: &str, decimals: u8) -> Option<U256> {
    let (whole, fraction) = text.split_once('.').unwrap_or((text, ""));
    let digits = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
    if !digits(whole) || (text.contains('.') && (!digits(fraction) || fraction.len() > 6)) {
        return None;
    }
    crate::types::Amount::parse_units(text, decimals).ok().map(crate::types::Amount::get)
}

#[cfg(test)]
mod tests;