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
//! Polymarket operation encoding and hashing, and Polymarket's signing domains.
//!
//! A Polymarket wallet shows only an operation's hash (`Op.data`); the SDK rebuilds it from the
//! typed data's unsigned `op`, whose terms the checks read.

use alloy_primitives::{B256, keccak256};
use alloy_sol_types::Eip712Domain;
use serde_json::Value;

use super::eip712;
use crate::deployments;

/// Polygon.
const CHAIN_ID: u64 = 137;
/// The only operation a send signs.
pub(crate) const INTERNAL_TRANSFER: &str = "internalTransfer";

/// Polymarket's withdrawal domain.
pub(crate) fn withdraw_domain() -> Eip712Domain {
    eip712::domain("Polymarket", "1", CHAIN_ID, Some(deployments::POLYMARKET_WITHDRAW_CONTRACT))
}

/// Polymarket's operation domain: no `verifyingContract` (absent, not zero).
pub(crate) fn operation_domain() -> Eip712Domain {
    eip712::domain("Polymarket", "1", CHAIN_ID, None)
}

/// `MessagePack` of `[name, [args…]]` for the only shape an operation hashes: strings shorter
/// than 256 bytes, at most 15 arguments. `None` for any other.
pub(crate) fn msgpack(name: &str, args: &[&str]) -> Option<Vec<u8>> {
    fn string(out: &mut Vec<u8>, text: &str) -> Option<()> {
        let length = u8::try_from(text.len()).ok()?;
        if length < 32 {
            out.push(0xa0 | length);
        } else {
            out.extend([0xd9, length]);
        }
        out.extend(text.as_bytes());
        Some(())
    }
    let count = u8::try_from(args.len()).ok().filter(|count| *count < 16)?;
    let mut out = vec![0x92];
    string(&mut out, name)?;
    out.push(0x90 | count);
    for arg in args {
        string(&mut out, arg)?;
    }
    Some(out)
}

/// An operation's `data`: keccak256 of its `MessagePack`, over the exact strings sent.
pub fn op_hash(name: &str, args: &[&str]) -> Option<B256> {
    msgpack(name, args).map(keccak256)
}

/// The internal transfer an operation's `op` names, its strings exactly as sent (addresses
/// checksummed, the amount in decimal pUSD).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct InternalTransfer {
    pub(crate) account: String,
    pub(crate) token: String,
    pub(crate) amount: String,
    pub(crate) to: String,
}

impl InternalTransfer {
    /// Reads `{"type": "internalTransfer", "args": {account, token, amount, to}}`, nothing else.
    pub(crate) fn read(op: &Value) -> Option<Self> {
        let op = op.as_object()?;
        if op.len() != 2 || op.get("type")?.as_str()? != INTERNAL_TRANSFER {
            return None;
        }
        let args = op.get("args")?.as_object()?;
        let text = |name: &str| args.get(name)?.as_str().map(str::to_owned);
        (args.len() == 4).then_some(())?;
        Some(Self {
            account: text("account")?,
            token: text("token")?,
            amount: text("amount")?,
            to: text("to")?,
        })
    }

    /// The `data` this transfer hashes to.
    pub(crate) fn hash(&self) -> Option<B256> {
        op_hash(INTERNAL_TRANSFER, &[&self.account, &self.token, &self.amount, &self.to])
    }
}

#[cfg(test)]
mod tests;