lamarge 0.5.1

Client for the LaMarge API: sign-in, takes, transfers, withdrawals and market making, each request checked before it is signed.
Documentation
//! Strict EIP-712 typed-data parsing and the signed `sol!` schemas.
//!
//! Every `typed_data` the server prepares is parsed against the schema the check expects: exact
//! top-level, domain, type and message keys, exact field types and order, and integer, address
//! and byte values of their declared width. What is signed is never the server's JSON but a
//! payload rebuilt from the checked struct and a pinned domain ([`typed`]), whose digest must
//! equal the server's.

use std::{borrow::Cow, collections::BTreeMap};

use alloy_dyn_abi::{DynSolValue, TypedData};
use alloy_primitives::{Address, B256, U256};
use alloy_sol_types::{Eip712Domain, SolStruct, SolValue};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

use super::checks::details::{self, differs};
use crate::{deployments, error::VerificationError};

/// The structs the SDK signs, as the escrow and the venues hash them.
mod schemas {
    alloy_sol_types::sol! {
        /// One quote of a quote set; `receive` is the EIP-712 field name (`receiveAmount` in
        /// Solidity).
        #[derive(Debug, PartialEq, Eq, serde::Serialize)]
        struct Quote {
            string venue;
            uint256 chainId;
            address token;
            address recipient;
            uint256 supply;
            uint256 receive;
            uint256 minFill;
        }

        /// A maker's signed quotes for one order.
        #[derive(Debug, PartialEq, Eq, serde::Serialize)]
        struct QuoteSet {
            address owner;
            bytes32 offerId;
            uint64 sequence;
            uint64 expiresAt;
            Quote[] quotes;
        }

        /// A maker's funding of an order.
        #[derive(Debug, PartialEq, Eq, serde::Serialize)]
        struct FundOffer {
            address owner;
            bytes32 offerId;
            uint256 amount;
            uint256 deposit;
            address quoteSigner;
            address operator;
            uint64 minQuoteSequence;
            uint256 nonce;
            uint256 deadline;
        }

        /// One payment of a take.
        #[derive(Debug, PartialEq, Eq, serde::Serialize)]
        struct LockPayment {
            address payer;
            bytes32 swapId;
            address recipient;
            uint256 amount;
            bytes32 hashlock;
            uint64 refundAt;
            uint256 deadline;
            bytes32 orderId;
            uint64 sequence;
            uint256 amountOut;
            uint256 receiveChainId;
            address receiveToken;
            address receiveEscrow;
            address receiveRecipient;
            uint32 dex;
        }

        /// A taker's payment of every fill of a take, after an optional deposit.
        #[derive(Debug, PartialEq, Eq, serde::Serialize)]
        struct PayTake {
            address payer;
            uint256 deposit;
            LockPayment[] payments;
        }

        /// An account's authorization to close its orders (checked by LaMarge only).
        #[derive(Debug, PartialEq, Eq, serde::Serialize)]
        struct CloseOrders {
            address account;
            bytes32[] orders;
            uint256 nonce;
            uint256 deadline;
        }

        /// An EIP-2612 permit.
        #[derive(Debug, PartialEq, Eq, serde::Serialize)]
        struct Permit {
            address owner;
            address spender;
            uint256 value;
            uint256 nonce;
            uint256 deadline;
        }

        /// A Polymarket withdrawal.
        #[derive(Debug, PartialEq, Eq, serde::Serialize)]
        struct Withdraw {
            address account;
            address token;
            uint256 amount;
            uint256 fee;
            address to;
            uint64 salt;
            uint64 ts;
        }

        /// A Polymarket operation: `data` hashes the operation the typed data's `op` names.
        #[derive(Debug, PartialEq, Eq, serde::Serialize)]
        struct Op {
            bytes32 data;
            uint64 salt;
            uint64 ts;
        }

        /// An Aster request: a query string.
        #[derive(Debug, PartialEq, Eq, serde::Serialize)]
        struct Message {
            string msg;
        }
    }
}

pub(crate) use schemas::*;

/// A primary type the SDK checks: its EIP-712 shape and how to read it from coerced values.
pub(crate) trait Schema: Sized {
    /// The primary type's name.
    const PRIMARY: &'static str;
    /// Whether the domain names a `verifyingContract` (Polymarket operations do not).
    const CONTRACT: bool = true;

    /// `encodeType` of the primary type: its fields, then the structs it references.
    fn encode_type() -> Cow<'static, str>;

    /// Reads the struct from the typed data's coerced message.
    fn decode(value: &DynSolValue) -> Option<Self>;
}

fn decode_sol<T: SolValue + From<<T::SolType as alloy_sol_types::SolType>::RustType>>(
    value: &DynSolValue,
) -> Option<T> {
    T::abi_decode(&value.abi_encode()).ok()
}

macro_rules! sol_schema {
    ($($schema:ident: $contract:literal),* $(,)?) => {$(
        impl Schema for $schema {
            const PRIMARY: &'static str = <$schema as SolStruct>::NAME;
            const CONTRACT: bool = $contract;

            fn encode_type() -> Cow<'static, str> {
                <$schema as SolStruct>::eip712_encode_type()
            }

            fn decode(value: &DynSolValue) -> Option<Self> {
                decode_sol(value)
            }
        }
    )*};
}

sol_schema!(
    QuoteSet: true,
    FundOffer: true,
    PayTake: true,
    CloseOrders: true,
    Permit: true,
    Withdraw: true,
    Message: true,
    Op: false,
);

/// A server `typed_data` read under its schema.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Parsed<T> {
    pub(crate) message: T,
    /// The digest of the server's typed data, as the server and the venue compute it.
    pub(crate) digest: B256,
}

/// Reads `raw` as typed data of schema `T`, refusing anything but its exact shape.
pub(crate) fn parse<T: Schema>(raw: &Value) -> Result<Parsed<T>, VerificationError> {
    parse_with(raw, false).map(|(parsed, _, _)| parsed)
}

/// [`parse`], signed in exactly `domain`.
pub(crate) fn parse_in<T: Schema>(
    raw: &Value,
    domain: &Eip712Domain,
) -> Result<Parsed<T>, VerificationError> {
    let (parsed, served, _) = parse_with(raw, false)?;
    if served == *domain { Ok(parsed) } else { Err(differs(details::DOMAIN)) }
}

/// Reads a Polymarket operation signed in `domain`: an [`Op`] whose typed data also carries the
/// unsigned `op` its `data` hashes, returned for its own check.
pub(crate) fn parse_operation<'a>(
    raw: &'a Value,
    domain: &Eip712Domain,
) -> Result<(Parsed<Op>, &'a Value), VerificationError> {
    let (parsed, served, op) = parse_with(raw, true)?;
    if served != *domain {
        return Err(differs(details::DOMAIN));
    }
    Ok((parsed, op.ok_or(differs(details::OP))?))
}

/// The parsed message, the served domain and, for an operation, its `op`.
type Read<'a, T> = (Parsed<T>, Eip712Domain, Option<&'a Value>);

fn parse_with<T: Schema>(raw: &Value, with_op: bool) -> Result<Read<'_, T>, VerificationError> {
    const KEYS: [&str; 4] = ["types", "primaryType", "domain", "message"];
    let object = raw.as_object().ok_or(differs(details::TYPED_DATA))?;
    let op = if with_op { object.get("op") } else { None };
    if object.len() != KEYS.len() + usize::from(op.is_some()) || !has_keys(object, &KEYS) {
        return Err(differs(details::TYPED_DATA));
    }
    let domain_types = domain_types(T::CONTRACT);
    let domain_keys: Vec<&str> = domain_types.iter().map(|(name, _)| *name).collect();
    let raw_domain = object["domain"].as_object().ok_or(differs(details::DOMAIN))?;
    if raw_domain.len() != domain_keys.len() || !has_keys(raw_domain, &domain_keys) {
        return Err(differs(details::DOMAIN));
    }
    if object["primaryType"] != T::PRIMARY {
        return Err(differs(details::PRIMARY_TYPE));
    }

    let encode_type = T::encode_type();
    let declared = raw_types(&object["types"]).ok_or(differs(details::TYPES))?;
    let mut names: Vec<&str> = struct_names(&encode_type).collect();
    names.push("EIP712Domain");
    if declared.len() != names.len()
        || !names.iter().all(|name| declared.contains_key(name))
        || declared["EIP712Domain"] != domain_types
    {
        return Err(differs(details::TYPES));
    }
    let typed = TypedData::deserialize(raw).map_err(|_| differs(details::TYPED_DATA))?;
    if typed.resolver.encode_type(T::PRIMARY).ok().as_deref() != Some(encode_type.as_ref()) {
        return Err(differs(details::TYPES));
    }

    if !fits(&declared, T::PRIMARY, &object["message"]) {
        return Err(differs(details::MESSAGE));
    }
    let value = typed.coerce().map_err(|_| differs(details::MESSAGE))?;
    let message = T::decode(&value).ok_or(differs(details::MESSAGE))?;
    let digest = typed.eip712_signing_hash().map_err(|_| differs(details::MESSAGE))?;
    Ok((Parsed { message, digest }, typed.domain, op))
}

fn has_keys(object: &Map<String, Value>, keys: &[&str]) -> bool {
    keys.iter().all(|key| object.contains_key(*key))
}

fn domain_types(contract: bool) -> Vec<(&'static str, &'static str)> {
    let mut fields = vec![("name", "string"), ("version", "string"), ("chainId", "uint256")];
    if contract {
        fields.push(("verifyingContract", "address"));
    }
    fields
}

/// The struct names an `encodeType` declares: `A(…)B(…)` names `A` and `B`.
fn struct_names(encode_type: &str) -> impl Iterator<Item = &str> {
    encode_type.split_terminator(')').filter_map(|part| part.split_once('(').map(|(name, _)| name))
}

type Types<'a> = BTreeMap<&'a str, Vec<(&'a str, &'a str)>>;

/// `types` as names to `(field, type)` lists; `None` unless each field is exactly
/// `{"name": …, "type": …}`.
fn raw_types(value: &Value) -> Option<Types<'_>> {
    value
        .as_object()?
        .iter()
        .map(|(name, fields)| {
            let fields = fields
                .as_array()?
                .iter()
                .map(|field| {
                    let field = field.as_object()?;
                    (field.len() == 2).then_some(())?;
                    Some((field.get("name")?.as_str()?, field.get("type")?.as_str()?))
                })
                .collect::<Option<Vec<_>>>()?;
            Some((name.as_str(), fields))
        })
        .collect()
}

/// Whether `value` is of EIP-712 type `kind`: structs with exactly their fields, arrays of
/// fitting items, and leaves of the declared width.
fn fits(types: &Types<'_>, kind: &str, value: &Value) -> bool {
    if let Some(item) = kind.strip_suffix("[]") {
        return value.as_array().is_some_and(|items| items.iter().all(|v| fits(types, item, v)));
    }
    if let Some(fields) = types.get(kind) {
        return value.as_object().is_some_and(|object| {
            object.len() == fields.len()
                && fields.iter().all(|(name, field)| {
                    object.get(*name).is_some_and(|value| fits(types, field, value))
                })
        });
    }
    match kind {
        "address" => value.as_str().is_some_and(|text| hex_of_length(text, 20)),
        "string" => value.is_string(),
        "bool" => value.is_boolean(),
        _ => {
            if let Some(width) = kind.strip_prefix("bytes") {
                let width = width.parse::<usize>().ok().filter(|width| (1..=32).contains(width));
                width.is_some_and(|width| {
                    value.as_str().is_some_and(|text| hex_of_length(text, width))
                })
            } else if let Some(bits) = kind.strip_prefix("uint") {
                let bits = if bits.is_empty() { Some(256) } else { bits.parse::<usize>().ok() };
                bits.filter(|bits| bits % 8 == 0 && (8..=256).contains(bits))
                    .is_some_and(|bits| unsigned(value).is_some_and(|n| n.bit_len() <= bits))
            } else {
                false
            }
        }
    }
}

/// `0x` and `2 × bytes` hexadecimal digits.
fn hex_of_length(text: &str, bytes: usize) -> bool {
    text.strip_prefix("0x").is_some_and(|digits| {
        digits.len() == 2 * bytes && digits.bytes().all(|b| b.is_ascii_hexdigit())
    })
}

/// An address written as `0x` and 40 hexadecimal digits, in any case (no checksum required).
pub(crate) fn address_text(text: &str) -> Option<Address> {
    if hex_of_length(text, 20) { text.parse().ok() } else { None }
}

/// A JSON integer or a decimal string of digits, as the server writes integers.
fn unsigned(value: &Value) -> Option<U256> {
    match value {
        Value::Number(number) => number.as_u64().map(U256::from),
        Value::String(text)
            if (1..=78).contains(&text.len()) && text.bytes().all(|b| b.is_ascii_digit()) =>
        {
            U256::from_str_radix(text, 10).ok()
        }
        _ => None,
    }
}

/// An EIP-712 domain built from pinned values.
pub(crate) fn domain(
    name: &'static str,
    version: &'static str,
    chain_id: u64,
    contract: Option<Address>,
) -> Eip712Domain {
    Eip712Domain::new(
        Some(Cow::Borrowed(name)),
        Some(Cow::Borrowed(version)),
        Some(U256::from(chain_id)),
        contract,
        None,
    )
}

/// The escrow's domain (`LaMarge`, version 1) on `chain_id`: a pinned escrow, or a venue's
/// signing domain.
pub(crate) fn lamarge_domain(chain_id: u64, contract: Address) -> Eip712Domain {
    domain("LaMarge", "1", chain_id, Some(contract))
}

/// The permit domain of `chain`'s token, if it has one.
pub(crate) fn permit_domain(chain: &deployments::Chain) -> Option<Eip712Domain> {
    let permit = chain.permit?;
    Some(domain(permit.name, permit.version, chain.id, Some(chain.token)))
}

/// The payload a signer is given: `message` under the pinned `domain`.
pub(crate) fn typed<T: SolStruct + Serialize>(message: &T, domain: Eip712Domain) -> TypedData {
    TypedData::from_struct(message, Some(domain))
}

#[cfg(test)]
mod tests;