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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
//! Each venue's own transfers out of an account, built and read without LaMarge's server, as the
//! TypeScript SDK's `hyperliquidSendAsset`, `polymarketWithdrawal`, `polymarketSend`,
//! `asterWithdrawal`, `asterSend` and `readVenueTransfer` build and read them.
//!
//! A builder pays whichever recipient its caller names, a contract wallet included; a host signing
//! with its own key decides who may receive. Builders return the typed data as JSON, in the shape
//! the TypeScript SDK and the server write, which [`read_venue_transfer`] and the checks read.

use alloy_primitives::{Address, U256};
use chrono::{DateTime, Utc};
use serde_json::{Value, json};

use super::{
    aster,
    checks::{
        details::{self, differs, unsupported},
        differs_unless, take,
        withdrawal::{ASTER_MAX_FEE_UNITS, positive},
    },
    eip712::{self, Withdraw},
    hyperliquid::{self, SendAsset},
    polymarket,
};
use crate::{
    deployments,
    error::VerificationError,
    types::{Amount, VenueId},
};

/// USDC's `HyperCore` system address: a `SendAsset` there credits the sender's own HyperEVM
/// address.
pub const HYPERLIQUID_BRIDGE: Address = deployments::HYPERLIQUID_BRIDGE;

/// What a venue transfer does.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TransferKind {
    /// Out of the venue onto a chain.
    Withdrawal,
    /// To another account of the same venue.
    Send,
}

/// A venue's own transfer out of an account, read from what its owner signs.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct VenueTransfer {
    /// The venue.
    pub venue: VenueId,
    /// A withdrawal or a send.
    pub kind: TransferKind,
    /// The account paying, when the payload names it: a Hyperliquid transfer's is its signer.
    pub account: Option<Address>,
    /// Who receives, when the payload names it: a Hyperliquid withdrawal pays its signer's own
    /// HyperEVM address.
    pub recipient: Option<Address>,
    /// A withdrawal's chain id.
    pub chain_id: Option<u64>,
    /// Base units that arrive.
    pub amount: Amount,
    /// Base units that leave the account: Aster adds its fee.
    pub cost: Amount,
    /// A Hyperliquid transfer's `sourceDex`: `""` perps, `spot` a unified account, `xyz` a
    /// standard account's trade.xyz.
    pub source_dex: Option<String>,
    /// An Aster send's `clientTranId`: Aster moves nothing more for a repeated one.
    pub id: Option<String>,
    /// When it was signed, from the venue's own unit.
    pub signed_at: DateTime<Utc>,
}

/// The `sourceDex` values a Hyperliquid transfer may leave from.
const SOURCE_DEXES: [&str; 3] = ["", "spot", "xyz"];
/// Polymarket's `Withdraw` fields, in order.
const WITHDRAW_FIELDS: [(&str, &str); 7] = [
    ("account", "address"),
    ("token", "address"),
    ("amount", "uint256"),
    ("fee", "uint256"),
    ("to", "address"),
    ("salt", "uint64"),
    ("ts", "uint64"),
];
/// Polymarket's `Op` fields, in order.
const OP_FIELDS: [(&str, &str); 3] = [("data", "bytes32"), ("salt", "uint64"), ("ts", "uint64")];
/// Aster's `Message` fields.
const MESSAGE_FIELDS: [(&str, &str); 1] = [("msg", "string")];
/// A domain's fields, with or without a contract.
const DOMAIN_FIELDS: [(&str, &str); 4] = [
    ("name", "string"),
    ("version", "string"),
    ("chainId", "uint256"),
    ("verifyingContract", "address"),
];

/// Reads a withdrawal or send out of an account on `venue` from its typed data, refusing any
/// field, domain, token or chain the venue's own transfer does not carry. It judges no recipient,
/// amount or time: the caller compares them with what it asked for.
pub fn read_venue_transfer(
    raw: &Value,
    venue: &VenueId,
) -> Result<VenueTransfer, VerificationError> {
    let primary = raw["primaryType"].as_str();
    if primary == Some("Op") && *venue != VenueId::Polymarket {
        return Err(differs(details::PRIMARY_TYPE));
    }
    match venue {
        VenueId::Hyperliquid => read_send_asset(raw),
        VenueId::Polymarket if primary == Some("Op") => read_internal_transfer(raw),
        VenueId::Polymarket => read_polymarket_withdrawal(raw),
        VenueId::Aster if primary == Some("Message") => read_aster_send(raw),
        VenueId::Aster => read_aster_withdrawal(raw),
        _ => Err(unsupported(details::VENUE)),
    }
}

fn read_send_asset(raw: &Value) -> Result<VenueTransfer, VerificationError> {
    let send = eip712::parse_in::<SendAsset>(raw, &hyperliquid::domain())?.message;
    let amount = deployments::decimal_units(&send.amount, deployments::HYPERLIQUID.decimals);
    let amount = amount.filter(|units| !units.is_zero()).map(Amount::new);
    differs_unless([
        (send.hyperliquid_chain == "Mainnet", details::HYPERLIQUID_CHAIN),
        (send.token == deployments::HYPERLIQUID_USDC, details::TOKEN),
        (send.from_sub_account.is_empty(), details::FROM_SUB_ACCOUNT),
        (SOURCE_DEXES.contains(&send.source_dex.as_str()), details::SOURCE_DEX),
        (amount.is_some(), details::AMOUNT),
    ])?;
    let amount = amount.ok_or(differs(details::AMOUNT))?;
    let signed_at = at_millis(send.nonce)?;
    let bridge = format!("{HYPERLIQUID_BRIDGE:#x}");
    let (kind, recipient, chain_id) =
        if send.destination.eq_ignore_ascii_case(&bridge) && send.destination_dex == "spot" {
            (TransferKind::Withdrawal, None, Some(hyperliquid::SIGNATURE_CHAIN_ID))
        } else {
            let recipient = eip712::address_text(&send.destination)
                .filter(|recipient| send.destination == format!("{recipient:#x}"))
                .filter(|_| !hyperliquid::is_system_address(&send.destination))
                .ok_or(differs(details::DESTINATION))?;
            if !["", "spot"].contains(&send.destination_dex.as_str()) {
                return Err(differs(details::DESTINATION_DEX));
            }
            (TransferKind::Send, Some(recipient), None)
        };
    Ok(VenueTransfer {
        venue: VenueId::Hyperliquid,
        kind,
        account: None,
        recipient,
        chain_id,
        amount,
        cost: amount,
        source_dex: Some(send.source_dex),
        id: None,
        signed_at,
    })
}

fn read_internal_transfer(raw: &Value) -> Result<VenueTransfer, VerificationError> {
    let (parsed, op) = eip712::parse_operation(raw, &polymarket::operation_domain())?;
    let transfer = polymarket::InternalTransfer::read(op).ok_or(differs(details::OP))?;
    let amount = deployments::decimal_units(&transfer.amount, deployments::POLYMARKET.decimals)
        .filter(|units| !units.is_zero())
        .map(Amount::new);
    let account = eip712::address_text(&transfer.account);
    let recipient = eip712::address_text(&transfer.to);
    differs_unless([
        (account.is_some(), details::ACCOUNT),
        (recipient.is_some(), details::TO),
        (
            eip712::address_text(&transfer.token) == Some(deployments::POLYMARKET.token),
            details::TOKEN,
        ),
        (transfer.hash() == Some(parsed.message.data), details::DATA),
    ])?;
    let amount = amount.ok_or(differs(details::AMOUNT))?;
    Ok(VenueTransfer {
        venue: VenueId::Polymarket,
        kind: TransferKind::Send,
        account,
        recipient,
        chain_id: None,
        amount,
        cost: amount,
        source_dex: None,
        id: None,
        signed_at: at_millis(parsed.message.ts)?,
    })
}

fn read_polymarket_withdrawal(raw: &Value) -> Result<VenueTransfer, VerificationError> {
    let withdraw = eip712::parse_in::<Withdraw>(raw, &polymarket::withdraw_domain())?.message;
    differs_unless([
        (withdraw.token == deployments::POLYMARKET.token, details::TOKEN),
        (withdraw.fee.is_zero(), details::FEE),
        (!withdraw.amount.is_zero(), details::AMOUNT),
    ])?;
    let amount = Amount::new(withdraw.amount);
    Ok(VenueTransfer {
        venue: VenueId::Polymarket,
        kind: TransferKind::Withdrawal,
        account: Some(withdraw.account),
        recipient: Some(withdraw.to),
        chain_id: Some(deployments::POLYMARKET.id),
        amount,
        cost: amount,
        source_dex: None,
        id: None,
        signed_at: at_seconds(withdraw.ts)?,
    })
}

fn read_aster_send(raw: &Value) -> Result<VenueTransfer, VerificationError> {
    let (_, transfer, _) = take::aster_transfer(raw)?;
    differs_unless([
        (is_client_id(&transfer.client_id), details::CLIENT_TRAN_ID),
        (!transfer.amount.is_zero(), details::AMOUNT),
    ])?;
    let amount = Amount::new(transfer.amount);
    Ok(VenueTransfer {
        venue: VenueId::Aster,
        kind: TransferKind::Send,
        account: Some(transfer.user),
        recipient: Some(transfer.to),
        chain_id: None,
        amount,
        cost: amount,
        source_dex: None,
        id: Some(transfer.client_id),
        signed_at: at_micros(transfer.nonce)?,
    })
}

fn read_aster_withdrawal(raw: &Value) -> Result<VenueTransfer, VerificationError> {
    let withdrawal =
        eip712::parse_in::<aster::Withdrawal>(raw, &aster::withdrawal_domain())?.message;
    let chain_id = aster::WITHDRAW_CHAINS
        .iter()
        .find(|(_, name)| *name == withdrawal.destination_chain)
        .map(|(id, _)| *id);
    let decimals = deployments::ASTER.decimals;
    let fee = deployments::decimal_units(&withdrawal.fee, decimals);
    let cost = deployments::decimal_units(&withdrawal.amount, decimals);
    let max_fee = U256::from(ASTER_MAX_FEE_UNITS) * deployments::ASTER.step();
    differs_unless([
        (withdrawal.kind == "Withdraw", details::TYPE),
        (chain_id.is_some(), details::DESTINATION_CHAIN),
        (withdrawal.token == aster::TOKEN, details::TOKEN),
        (withdrawal.aster_chain == "Mainnet", details::ASTER_CHAIN),
        (fee.is_some_and(|fee| fee <= max_fee), details::FEE),
    ])?;
    let (cost, fee) =
        cost.zip(fee).filter(|(cost, fee)| cost > fee).ok_or(differs(details::AMOUNT))?;
    let nonce = u64::try_from(withdrawal.nonce).map_err(|_| differs(details::NONCE))?;
    Ok(VenueTransfer {
        venue: VenueId::Aster,
        kind: TransferKind::Withdrawal,
        account: Some(withdrawal.destination),
        recipient: Some(withdrawal.destination),
        chain_id,
        amount: Amount::new(cost - fee),
        cost: Amount::new(cost),
        source_dex: None,
        id: None,
        signed_at: at_micros(nonce)?,
    })
}

/// Hyperliquid's `SendAsset` of `amount` USDC from an account's main balance: to `recipient`,
/// another account, or without one to the signer's own HyperEVM address. `nonce` in
/// milliseconds, 2^53 − 1 at most; `source_dex` `""` perps, `spot` a unified account, `xyz` a standard account's
/// trade.xyz.
pub fn hyperliquid_send_asset(
    amount: Amount,
    nonce: u64,
    source_dex: &str,
    recipient: Option<Address>,
) -> Result<Value, VerificationError> {
    if !SOURCE_DEXES.contains(&source_dex) {
        return Err(differs(details::SOURCE_DEX));
    }
    let destination = match recipient {
        Some(recipient) if hyperliquid::is_system_address(&format!("{recipient:#x}")) => {
            return Err(differs(details::RECIPIENT));
        }
        Some(recipient) => format!("{recipient:#x}"),
        None => format!("{HYPERLIQUID_BRIDGE:#x}"),
    };
    let send = SendAsset {
        hyperliquid_chain: "Mainnet".to_owned(),
        destination,
        source_dex: source_dex.to_owned(),
        destination_dex: if recipient.is_some() { String::new() } else { "spot".to_owned() },
        token: deployments::HYPERLIQUID_USDC.to_owned(),
        amount: decimal_text(positive(amount)?, deployments::HYPERLIQUID.decimals)?,
        from_sub_account: String::new(),
        nonce: positive_time(nonce)?,
    };
    let message = json!({
        "hyperliquidChain": send.hyperliquid_chain,
        "destination": send.destination,
        "sourceDex": send.source_dex,
        "destinationDex": send.destination_dex,
        "token": send.token,
        "amount": send.amount,
        "fromSubAccount": send.from_sub_account,
        "nonce": send.nonce,
    });
    let domain = domain_json(
        "HyperliquidSignTransaction",
        hyperliquid::SIGNATURE_CHAIN_ID,
        Some(Address::ZERO),
    );
    Ok(typed_json(&domain, hyperliquid::PRIMARY, &hyperliquid::FIELDS, &message))
}

/// Polymarket's withdrawal of `amount` pUSD from `account`'s Perps margin to `recipient` on
/// Polygon, without fee; `ts` in seconds. `salt` and `ts` are 2^53 − 1 at most, as a JSON number
/// keeps them exactly.
pub fn polymarket_withdrawal(
    account: Address,
    recipient: Address,
    amount: Amount,
    salt: u64,
    ts: u64,
) -> Result<Value, VerificationError> {
    let message = json!({
        "account": account.to_checksum(None),
        "token": deployments::POLYMARKET.token.to_checksum(None),
        "amount": positive(amount)?.to_string(),
        "fee": "0",
        "to": recipient.to_checksum(None),
        "salt": safe_salt(salt)?,
        "ts": positive_time(ts)?,
    });
    let domain = domain_json(
        "Polymarket",
        deployments::POLYMARKET.id,
        Some(deployments::POLYMARKET_WITHDRAW_CONTRACT),
    );
    Ok(typed_json(&domain, "Withdraw", &WITHDRAW_FIELDS, &message))
}

/// Polymarket's internal transfer of `amount` pUSD from `account` to `recipient`'s Perps
/// account; `ts` in milliseconds, `salt` and `ts` 2^53 − 1 at most. Its `op` travels with the
/// typed data: a wallet is shown only the hash of it.
pub fn polymarket_send(
    account: Address,
    recipient: Address,
    amount: Amount,
    salt: u64,
    ts: u64,
) -> Result<Value, VerificationError> {
    let transfer = polymarket::InternalTransfer {
        account: account.to_checksum(None),
        token: deployments::POLYMARKET.token.to_checksum(None),
        amount: decimal_text(positive(amount)?, deployments::POLYMARKET.decimals)?,
        to: recipient.to_checksum(None),
    };
    let data = transfer.hash().ok_or(differs(details::OP))?;
    let message = json!({
        "data": format!("{data:#x}"),
        "salt": safe_salt(salt)?,
        "ts": positive_time(ts)?,
    });
    let domain = domain_json("Polymarket", deployments::POLYMARKET.id, None);
    let mut typed = typed_json(&domain, "Op", &OP_FIELDS, &message);
    typed["op"] = json!({
        "type": polymarket::INTERNAL_TRANSFER,
        "args": {
            "account": transfer.account,
            "token": transfer.token,
            "amount": transfer.amount,
            "to": transfer.to,
        },
    });
    Ok(typed)
}

/// Aster's withdrawal from `account` to its own address on `chain_id` (BSC, Arbitrum or
/// Ethereum): `amount` arrives, `fee` on top, both whole millionths of USDT, the fee 2 USDT at
/// most. `nonce`: microseconds, 16 digits. Aster relays it in an envelope the account signs
/// second.
pub fn aster_withdrawal(
    account: Address,
    chain_id: u64,
    amount: Amount,
    fee: Amount,
    nonce: u64,
) -> Result<Value, VerificationError> {
    let chain = aster::withdraw_chain_name(chain_id).ok_or(differs(details::DESTINATION_CHAIN))?;
    let max_fee = U256::from(ASTER_MAX_FEE_UNITS) * deployments::ASTER.step();
    if fee.get() > max_fee {
        return Err(differs(details::FEE));
    }
    let cost = positive(amount)?.checked_add(fee.get()).ok_or(differs(details::AMOUNT))?;
    let decimals = deployments::ASTER.decimals;
    let withdrawal = aster::Withdrawal {
        kind: "Withdraw".to_owned(),
        destination: account,
        destination_chain: chain.to_owned(),
        token: aster::TOKEN.to_owned(),
        amount: decimal_text(cost, decimals)?,
        fee: decimal_text(fee.get(), decimals)?,
        nonce: U256::from(micros_nonce(nonce)?),
        aster_chain: "Mainnet".to_owned(),
    };
    let message = json!({
        "type": withdrawal.kind,
        "destination": format!("{:#x}", withdrawal.destination),
        "destination Chain": withdrawal.destination_chain,
        "token": withdrawal.token,
        "amount": withdrawal.amount,
        "fee": withdrawal.fee,
        "nonce": withdrawal.nonce.to_string(),
        "aster chain": withdrawal.aster_chain,
    });
    let domain = domain_json("Aster", aster::CHAIN_ID, Some(Address::ZERO));
    Ok(typed_json(&domain, aster::WITHDRAWAL_PRIMARY, &aster::WITHDRAWAL_FIELDS, &message))
}

/// Aster's transfer of `amount` USDT, whole millionths, from `account`'s Spot wallet to
/// `recipient`'s, under `id` (letters and digits, 64 at most); `nonce`: microseconds, 16 digits.
pub fn aster_send(
    account: Address,
    recipient: Address,
    amount: Amount,
    id: &str,
    nonce: u64,
) -> Result<Value, VerificationError> {
    if !is_client_id(id) {
        return Err(differs(details::CLIENT_TRAN_ID));
    }
    let msg = format!(
        "asset={}&amount={}&toAddress={}&clientTranId={id}&nonce={}&user={}",
        aster::TOKEN,
        decimal_text(positive(amount)?, deployments::ASTER.decimals)?,
        recipient.to_checksum(None),
        micros_nonce(nonce)?,
        account.to_checksum(None),
    );
    let domain = domain_json("AsterSignTransaction", aster::TRANSFER_CHAIN_ID, Some(Address::ZERO));
    Ok(typed_json(&domain, "Message", &MESSAGE_FIELDS, &json!({ "msg": msg })))
}

/// `units` of a token with `decimals` as the decimal text venues sign, six decimals at most,
/// exactly: `"5"`, `"5.25"`. Refused (`Differs`, `amount`) when it needs more decimals.
pub fn decimal_text(units: U256, decimals: u8) -> Result<String, VerificationError> {
    let step = U256::from(10u8).pow(U256::from(decimals.saturating_sub(6)));
    if !(units % step).is_zero() {
        return Err(differs(details::AMOUNT));
    }
    Ok(Amount::new(units).format_units(decimals))
}

/// The largest integer a JSON number keeps exactly, as the TypeScript SDK's `Number.isSafeInteger`.
const MAX_SAFE_INTEGER: u64 = (1 << 53) - 1;

/// A time as a JSON number: positive and kept exactly.
fn positive_time(value: u64) -> Result<u64, VerificationError> {
    if (1..=MAX_SAFE_INTEGER).contains(&value) { Ok(value) } else { Err(differs(details::NONCE)) }
}

/// A Polymarket salt as a JSON number, kept exactly.
fn safe_salt(salt: u64) -> Result<u64, VerificationError> {
    if salt <= MAX_SAFE_INTEGER { Ok(salt) } else { Err(differs(details::SALT)) }
}

/// An Aster `clientTranId` the builders write: letters and digits, 64 at most.
fn is_client_id(id: &str) -> bool {
    (1..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_alphanumeric())
}

/// A nonce as Aster writes it: microseconds, 16 digits.
fn micros_nonce(nonce: u64) -> Result<u64, VerificationError> {
    if (1_000_000_000_000_000..10_000_000_000_000_000).contains(&nonce) {
        Ok(nonce)
    } else {
        Err(differs(details::NONCE))
    }
}

fn at_seconds(seconds: u64) -> Result<DateTime<Utc>, VerificationError> {
    i64::try_from(seconds)
        .ok()
        .and_then(|seconds| DateTime::from_timestamp(seconds, 0))
        .ok_or(differs(details::NONCE))
}

fn at_millis(millis: u64) -> Result<DateTime<Utc>, VerificationError> {
    i64::try_from(millis)
        .ok()
        .and_then(DateTime::from_timestamp_millis)
        .ok_or(differs(details::NONCE))
}

fn at_micros(micros: u64) -> Result<DateTime<Utc>, VerificationError> {
    i64::try_from(micros)
        .ok()
        .and_then(DateTime::from_timestamp_micros)
        .ok_or(differs(details::NONCE))
}

/// A domain as JSON, its chain id a number.
fn domain_json(name: &str, chain_id: u64, contract: Option<Address>) -> Value {
    let mut domain = json!({ "name": name, "version": "1", "chainId": chain_id });
    if let Some(contract) = contract {
        domain["verifyingContract"] = json!(format!("{contract:#x}"));
    }
    domain
}

/// Typed data as JSON: `message`, of `fields`, under `domain`.
fn typed_json(domain: &Value, primary: &str, fields: &[(&str, &str)], message: &Value) -> Value {
    let props = |fields: &[(&str, &str)]| -> Vec<Value> {
        fields.iter().map(|(name, kind)| json!({ "name": name, "type": kind })).collect()
    };
    let domain_fields = if domain.get("verifyingContract").is_some() {
        &DOMAIN_FIELDS[..]
    } else {
        &DOMAIN_FIELDS[..3]
    };
    json!({
        "types": { "EIP712Domain": props(domain_fields), primary: props(fields) },
        "primaryType": primary,
        "domain": domain,
        "message": message,
    })
}

#[cfg(test)]
mod tests;