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
//! Aster requests: query-string fields, transfer amounts and client ids, nonce windows, and
//! Aster's signing domain.
//!
//! Aster signs `Message{msg}` where `msg` is a query string; a transfer between accounts signs
//! it at chain 1666 (no such chain exists), approvals and withdrawals at BSC's 56.

use std::{borrow::Cow, ops::RangeInclusive};

use alloy_dyn_abi::{DynSolValue, TypedData};
use alloy_primitives::{Address, U256};
use alloy_sol_types::Eip712Domain;
use serde_json::json;

use super::eip712::{self, Schema};
use crate::{deployments, types::FillId};

/// BSC: the signing chain of withdrawals and agent approvals, and the default withdrawal chain.
pub const CHAIN_ID: u64 = 56;
/// The chains a withdrawal may go to, as (chain id, Aster's name in `destination Chain`).
pub(crate) const WITHDRAW_CHAINS: [(u64, &str); 3] = [(56, "BSC"), (42161, "Arbitrum"), (1, "ETH")];

/// Aster's name of withdrawal chain `chain_id`.
pub(crate) fn withdraw_chain_name(chain_id: u64) -> Option<&'static str> {
    WITHDRAW_CHAINS.iter().find(|(id, _)| *id == chain_id).map(|(_, name)| *name)
}
/// The chain id of transfers between accounts.
pub const TRANSFER_CHAIN_ID: u64 = 1666;
/// The token Aster moves.
pub(crate) const TOKEN: &str = "USDT";
/// A take's transfer is signed while its nonce is at least this many seconds ahead.
pub(crate) const NONCE_AHEAD_SECONDS: i64 = 20;
/// A transfer's nonce may lead `now` by this much while its `pay_by` is sooner.
const NONCE_LEAD_SECONDS: i64 = 70;

const MICROS: i128 = 1_000_000;

/// `AsterSignTransaction`, version 1, at `chain_id`, the zero address as contract.
pub(crate) fn domain(chain_id: u64) -> Eip712Domain {
    eip712::domain("AsterSignTransaction", "1", chain_id, Some(Address::ZERO))
}

/// The primary type of a withdrawal.
pub(crate) const WITHDRAWAL_PRIMARY: &str = "Action";
/// A withdrawal's fields, in order: Aster's names, two with a space.
pub(crate) const WITHDRAWAL_FIELDS: [(&str, &str); 8] = [
    ("type", "string"),
    ("destination", "address"),
    ("destination Chain", "string"),
    ("token", "string"),
    ("amount", "string"),
    ("fee", "string"),
    ("nonce", "uint256"),
    ("aster chain", "string"),
];

/// The domain of a withdrawal: `Aster`, version 1, at BSC's chain id, the zero address as
/// contract.
pub(crate) fn withdrawal_domain() -> Eip712Domain {
    eip712::domain("Aster", "1", CHAIN_ID, Some(Address::ZERO))
}

/// A withdrawal from an Aster account to BSC (`Action`), as its owner signs it. An SDK-owned
/// schema: its field names are no Rust identifiers for `sol!`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Withdrawal {
    /// `type`: `Withdraw`.
    pub(crate) kind: String,
    pub(crate) destination: Address,
    pub(crate) destination_chain: String,
    pub(crate) token: String,
    /// Decimal USDT, the fee included.
    pub(crate) amount: String,
    /// Decimal USDT, taken out of `amount`.
    pub(crate) fee: String,
    /// Microseconds.
    pub(crate) nonce: U256,
    pub(crate) aster_chain: String,
}

impl Withdrawal {
    /// The payload a signer is given: these values under the withdrawal domain.
    pub(crate) fn typed_data(&self) -> TypedData {
        eip712::custom_typed(
            withdrawal_domain(),
            WITHDRAWAL_PRIMARY,
            &WITHDRAWAL_FIELDS,
            json!({
                "type": self.kind,
                "destination": format!("{:#x}", self.destination),
                "destination Chain": self.destination_chain,
                "token": self.token,
                "amount": self.amount,
                "fee": self.fee,
                "nonce": self.nonce.to_string(),
                "aster chain": self.aster_chain,
            }),
        )
    }
}

impl Schema for Withdrawal {
    const PRIMARY: &'static str = WITHDRAWAL_PRIMARY;

    fn encode_type() -> Cow<'static, str> {
        eip712::custom_encode_type(WITHDRAWAL_PRIMARY, &WITHDRAWAL_FIELDS)
    }

    fn decode(value: &DynSolValue) -> Option<Self> {
        let (_, _, values) = value.as_custom_struct()?;
        let [kind, destination, destination_chain, token, amount, fee, nonce, aster_chain] = values
        else {
            return None;
        };
        let text = |value: &DynSolValue| value.as_str().map(str::to_owned);
        Some(Self {
            kind: text(kind)?,
            destination: destination.as_address()?,
            destination_chain: text(destination_chain)?,
            token: text(token)?,
            amount: text(amount)?,
            fee: text(fee)?,
            nonce: nonce.as_uint()?.0,
            aster_chain: text(aster_chain)?,
        })
    }
}

/// The values of `msg`'s `name=value` pairs, which must be exactly `names` in order.
pub(crate) fn fields<'a>(msg: &'a str, names: &[&str]) -> Option<Vec<&'a str>> {
    let pairs: Vec<&str> = msg.split('&').collect();
    if pairs.len() != names.len() {
        return None;
    }
    pairs
        .into_iter()
        .zip(names)
        .map(|(pair, name)| match pair.split_once('=') {
            Some((key, value)) if key == *name && !value.contains('=') => Some(value),
            _ => None,
        })
        .collect()
}

/// A nonce as Aster writes it: microseconds, 16 digits.
pub(crate) fn parse_nonce(text: &str) -> Option<u64> {
    if text.len() == 16 && text.bytes().all(|b| b.is_ascii_digit()) {
        text.parse().ok()
    } else {
        None
    }
}

/// Whether a microsecond `nonce` is within `skew` seconds of `now` (Unix seconds), exactly.
pub(crate) fn nonce_near(nonce: u64, now: i64, skew: i64) -> bool {
    nonce_near_micros(nonce, i128::from(now) * MICROS, skew)
}

/// Whether a microsecond `nonce` is within `skew` seconds of `now` (Unix microseconds), exactly.
pub(crate) fn nonce_near_micros(nonce: u64, now: i128, skew: i64) -> bool {
    (i128::from(nonce) - now).abs() <= i128::from(skew) * MICROS
}

/// The microsecond nonces a take's transfer may carry: far enough ahead for LaMarge to relay it,
/// and no later than Aster accepts when relayed by `pay_by` (Unix seconds, as `now`).
pub(crate) fn transfer_nonce_window(now: i64, pay_by: i64) -> RangeInclusive<i128> {
    let earliest = i128::from(now) + i128::from(NONCE_AHEAD_SECONDS);
    let latest = (i128::from(now) + i128::from(NONCE_LEAD_SECONDS))
        .max(i128::from(pay_by) + i128::from(NONCE_AHEAD_SECONDS));
    earliest * MICROS..=latest * MICROS
}

/// The `clientTranId` of a fill's transfer: its id in 32 lowercase hex digits. Aster moves
/// nothing more for a repeated one.
pub fn client_id(fill: FillId) -> String {
    fill.as_uuid().simple().to_string()
}

/// A transfer between accounts, read from its `msg`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Transfer {
    /// Base units (18 decimals).
    pub amount: U256,
    /// The account paid (`toAddress`).
    pub to: Address,
    /// The transfer's id (`clientTranId`): Aster moves nothing more for a repeated one.
    pub client_id: String,
    /// The nonce, in Unix microseconds as Aster writes it (the TypeScript SDK's `nonce` is in
    /// seconds).
    pub nonce: u64,
    /// The account paying.
    pub user: Address,
}

/// Reads `asset=USDT&amount=…&toAddress=…&clientTranId=…&nonce=…&user=…`, nothing else.
pub(crate) fn parse_transfer(msg: &str) -> Option<Transfer> {
    let names = ["asset", "amount", "toAddress", "clientTranId", "nonce", "user"];
    let values = fields(msg, &names)?;
    let [asset, amount, to, client_id, nonce, user] = values[..] else { return None };
    if asset != TOKEN {
        return None;
    }
    Some(Transfer {
        amount: deployments::decimal_units(amount, deployments::ASTER.decimals)?,
        to: eip712::address_text(to)?,
        client_id: client_id.to_owned(),
        nonce: parse_nonce(nonce)?,
        user: eip712::address_text(user)?,
    })
}

#[cfg(test)]
mod tests;