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
use serde_json::{Value, json};

use super::*;
use crate::{
    error::VerificationKind,
    testing::{
        self, MAKER, NOW, OPERATOR, OTHER, OWNER, POOL, edited,
        fixtures::{self, funded},
        json::fixture,
    },
};

fn check_with(
    prepared: &Value,
    request: &CapitalRequest,
    existing: Option<&Order>,
) -> Result<Vec<Verified>, VerificationError> {
    let authority = fixtures::authority(existing);
    check_maker_intent(
        &fixtures::maker(prepared),
        request,
        &authority,
        EscrowEnvironment::Production,
        fixtures::now(),
    )
}

fn check(prepared: &Value) -> Result<Vec<Verified>, VerificationError> {
    check_with(prepared, &fixtures::capital_request(FundingSource::Wallet), None)
}

fn fund(prepared: &mut Value) -> &mut Value {
    &mut prepared["to_sign"][0]["typed_data"]["message"]
}

fn fund_domain(prepared: &mut Value) -> &mut Value {
    &mut prepared["to_sign"][0]["typed_data"]["domain"]
}

/// Development's escrow on HyperEVM.
const DEV_HL: &str = "0x948e65c40442d935d4ee990bdbd01bdd825c4873";

/// `intents.test.ts` "financial provisioning permits only the requested authority, domain,
/// capital and request id"; `maker.test.ts` "malicious operator authority is rejected before
/// the first master signature", "funding against an unpinned escrow never reaches the
/// financial key".
#[test]
fn a_funding_binds_only_the_requested_authority_domain_capital_and_request() {
    let verified = check(&fixtures::maker_preparation()).unwrap();
    assert_eq!(verified.len(), 1);
    assert_eq!(verified[0].not_after(), Some(NOW + 3570));
    let prepared = |edit: fn(&mut Value)| edited(fixtures::maker_preparation(), edit);
    let item = fixtures::maker_preparation()["to_sign"][0].clone();
    let max = U256::MAX.to_string();
    let cases = [
        (funded("operator", json!(OWNER)), details::FUND_OPERATOR),
        (funded("quoteSigner", json!(OPERATOR)), details::FUND_QUOTE_SIGNER),
        (funded("amount", json!("10000001")), details::FUND_AMOUNT),
        (funded("deposit", json!("9999999")), details::FUND_DEPOSIT),
        (funded("owner", json!(OTHER)), details::FUND_OWNER),
        (funded("offerId", json!(testing::ORDER)), details::FUND_OFFER_ID),
        (funded("minQuoteSequence", json!(0)), details::FUND_MIN_QUOTE_SEQUENCE),
        (funded("minQuoteSequence", json!(1u64 << 53)), details::FUND_MIN_QUOTE_SEQUENCE),
        (funded("deadline", json!((NOW + 7200).to_string())), details::DEADLINE),
        (funded("deadline", json!(NOW.to_string())), details::DEADLINE),
        (prepared(|p| fund_domain(p)["verifyingContract"] = json!(OWNER)), details::DOMAIN),
        (prepared(|p| fund_domain(p)["chainId"] = json!(137)), details::DOMAIN),
        (prepared(|p| fund_domain(p)["verifyingContract"] = json!(DEV_HL)), details::DOMAIN),
        (
            prepared(|p| {
                p["to_sign"][0]["typed_data"]["types"]["FundOffer"][2]["type"] = json!("uint64");
            }),
            details::TYPES,
        ),
        (prepared(|p| p["to_sign"][0]["signer"] = json!(OPERATOR)), details::FUND_SIGNER),
        (prepared(|p| p["client_request_id"] = json!("another")), details::CLIENT_REQUEST_ID),
        (
            edited(fixtures::maker_preparation(), |p| p["to_sign"] = json!([item, item])),
            details::TO_SIGN,
        ),
        (prepared(|p| p["to_sign"] = json!([])), details::TO_SIGN),
        (prepared(|p| p["state"] = json!("accepted")), details::STATE),
        (prepared(|p| p["venue"] = json!("polymarket")), details::VENUE),
        (prepared(|p| p["order"]["owner_address"] = json!(OTHER)), details::ORDER_OWNER_ADDRESS),
        (prepared(|p| p["order"]["quote_signer"] = json!(OTHER)), details::ORDER_QUOTE_SIGNER),
        (
            prepared(|p| p["order"]["quote_identity_id"] = json!(testing::FILL)),
            details::ORDER_QUOTE_IDENTITY_ID,
        ),
        (prepared(|p| p["intent"]["amount"] = json!("1")), details::INTENT_AMOUNT),
        (
            prepared(|p| p["intent"]["quote_identity_id"] = json!(testing::FILL)),
            details::INTENT_QUOTE_IDENTITY_ID,
        ),
        (
            prepared(|p| p["intent"]["funding_source"] = json!("venue")),
            details::INTENT_FUNDING_SOURCE,
        ),
        (prepared(|p| p["expected_revision"] = json!("2")), details::EXPECTED_REVISION),
        (prepared(|p| p["expires_at"] = json!(testing::time(3631))), details::EXPIRES_AT),
        (prepared(|p| p["order"]["last_sequence"] = json!(3)), details::ORDER),
        (prepared(|p| p["sequence"] = json!(2)), details::SEQUENCE),
        (prepared(|p| p["funding"]["venue_amount"] = json!("1")), details::FUNDING_IDLE_AMOUNT),
        // A deposit beyond the largest integer refuses rather than wraps.
        (
            edited(fixtures::maker_preparation(), |p| {
                p["funding"]["wallet_amount"] = json!(max);
                p["funding"]["venue_amount"] = json!("1");
            }),
            details::FUNDING_DEPOSIT,
        ),
    ];
    for (index, (prepared, detail)) in cases.iter().enumerate() {
        assert_eq!(check(prepared).unwrap_err().detail, *detail, "case {index}");
    }
    // The operator comes from the caller: the API's never authorizes another.
    let elsewhere = MakerAuthority { operator: OTHER, ..fixtures::authority(None) };
    let error = check_maker_intent(
        &fixtures::maker(&fixtures::maker_preparation()),
        &fixtures::capital_request(FundingSource::Wallet),
        &elsewhere,
        EscrowEnvironment::Production,
        fixtures::now(),
    );
    assert_eq!(error.unwrap_err().detail, details::FUND_OPERATOR);
}

/// `intents.test.ts` "a deposit takes the available balance first and only the rest from its
/// source".
#[test]
fn a_deposit_takes_the_available_balance_first() {
    let idle = |patch: &Value, deposit: &str| {
        edited(fixtures::maker_preparation(), |p| {
            let mut funding = json!({"existing_available": "4000000", "idle_amount": "4000000", "wallet_amount": "6000000"});
            fixtures::object(&mut funding).extend(patch.as_object().unwrap().clone());
            fixtures::object(&mut p["funding"]).extend(funding.as_object().unwrap().clone());
            fund(p)["deposit"] = json!(deposit);
        })
    };
    assert!(check(&idle(&json!({}), "6000000")).is_ok());
    let cases = [
        (json!({"existing_available": "3000000"}), "6000000", details::FUNDING_DEPOSIT),
        (
            json!({"idle_amount": "0", "wallet_amount": "10000000"}),
            "10000000",
            details::FUNDING_DEPOSIT,
        ),
        (
            json!({"idle_amount": "3000000", "wallet_amount": "7000000"}),
            "7000000",
            details::FUNDING_DEPOSIT,
        ),
        (
            json!({"idle_amount": "4000000", "wallet_amount": "7000000"}),
            "7000000",
            details::FUNDING_IDLE_AMOUNT,
        ),
    ];
    for (patch, deposit, detail) in cases {
        assert_eq!(check(&idle(&patch, deposit)).unwrap_err().detail, detail, "{patch}");
    }
}

/// A top-up of the identity's pool: what it had available stays its own, and capital that
/// moved since the pool was read is reviewed again.
#[test]
fn a_top_up_binds_the_pool_as_it_was_read() {
    let live = |edit: fn(&mut Value)| -> Order {
        let mut pool = fixtures::pool();
        pool["state"] = json!("live");
        pool["available_to_quote"] = json!("4000000");
        edit(&mut pool);
        fixtures::model(&pool)
    };
    let prepared = edited(fixtures::maker_preparation(), |p| {
        p["order"]["available_to_quote"] = json!("4000000");
        p["funding"]["existing_available"] = json!("4000000");
    });
    let request = fixtures::capital_request(FundingSource::Wallet);
    let existing = live(|_| {});
    assert!(check_with(&prepared, &request, Some(&existing)).is_ok());
    assert_eq!(check(&prepared).unwrap_err().detail, details::ORDER);
    let below = edited(prepared.clone(), |p| p["funding"]["existing_available"] = json!("3999999"));
    assert_eq!(
        check_with(&below, &request, Some(&existing)).unwrap_err().detail,
        details::FUNDING_EXISTING_AVAILABLE
    );
    let moved = live(|pool| pool["available_to_quote"] = json!("5000000"));
    let error = check_with(&prepared, &request, Some(&moved)).unwrap_err();
    assert_eq!((error.kind, error.detail), (VerificationKind::Changed, details::MAKER_CAPITAL));
    let newer = live(|pool| pool["revision"] = json!("2"));
    assert_eq!(
        check_with(&prepared, &request, Some(&newer)).unwrap_err().detail,
        details::MAKER_CAPITAL
    );
    let other = live(|pool| pool["id"] = json!(testing::ORDER));
    assert_eq!(
        check_with(&prepared, &request, Some(&other)).unwrap_err().detail,
        details::ORDER_ID
    );
    let foreign = live(|pool| pool["quote_signer"] = json!(OTHER));
    assert_eq!(
        check_with(&prepared, &request, Some(&foreign)).unwrap_err().detail,
        details::EXISTING_ORDER
    );
}

#[test]
fn venue_funding_moves_the_whole_deposit_out_of_margin_once() {
    let request = fixtures::capital_request(FundingSource::Venue);
    let verified = check_with(&fixtures::margin_preparation(), &request, None).unwrap();
    assert_eq!(verified.len(), 2);
    let served = eip712::parse::<crate::protocol::hyperliquid::SendAsset>(
        &fixtures::margin_preparation()["to_sign"][0]["typed_data"],
    )
    .unwrap();
    assert_eq!(verified[0].digest(), served.digest);
    let cases = [
        (
            edited(fixtures::margin_preparation(), |p| {
                p["to_sign"][0]["signer"] = json!(OTHER);
            }),
            details::MARGIN_MOVE_SIGNER,
        ),
        (
            edited(fixtures::margin_preparation(), |p| {
                p["to_sign"][0]["typed_data"]["message"]["amount"] = json!("9");
            }),
            details::MARGIN_MOVE_AMOUNT,
        ),
        (
            edited(fixtures::margin_preparation(), |p| {
                p["to_sign"][0]["typed_data"]["message"]["destination"] =
                    json!(format!("{OTHER:#x}"));
            }),
            details::DESTINATION,
        ),
        (
            edited(fixtures::margin_preparation(), |p| {
                p["funding"]["wallet_amount"] = json!("1");
            }),
            details::FUNDING_IDLE_AMOUNT,
        ),
        (
            edited(fixtures::margin_preparation(), |p| {
                let fund = p["to_sign"][1].clone();
                p["to_sign"] = json!([fund]);
            }),
            details::TO_SIGN,
        ),
    ];
    for (index, (prepared, detail)) in cases.iter().enumerate() {
        assert_eq!(
            check_with(prepared, &request, None).unwrap_err().detail,
            *detail,
            "case {index}"
        );
    }
    let wallet_with_move = edited(fixtures::margin_preparation(), |p| {
        p["intent"]["funding_source"] = json!("wallet");
    });
    let error =
        check_with(&wallet_with_move, &fixtures::capital_request(FundingSource::Wallet), None);
    assert_eq!(error.unwrap_err().detail, details::FUNDING_VENUE_AMOUNT);
    let venue_from_wallet = edited(fixtures::maker_preparation(), |p| {
        p["intent"]["funding_source"] = json!("venue");
    });
    assert_eq!(
        check_with(&venue_from_wallet, &request, None).unwrap_err().detail,
        details::FUNDING_WALLET_AMOUNT
    );
}

/// A delegated identity's quotes are never re-signed by a capital addition;
/// `intents.test.ts`'s browser top-up is deferred.
#[test]
fn a_delegated_addition_signs_no_quote_set() {
    let quote =
        json!({"kind": "quote_set", "signer": MAKER, "typed_data": testing::sample("quote_set")});
    let prepared = edited(fixtures::maker_preparation(), |p| {
        p["to_sign"].as_array_mut().unwrap().push(quote);
        p["sequence"] = json!(12);
    });
    assert_eq!(check(&prepared).unwrap_err().detail, details::TO_SIGN);
    // Lighter and Aster pools are settled inside the venue: not funded here.
    let lighter = CapitalRequest {
        venue: VenueId::Lighter,
        ..fixtures::capital_request(FundingSource::Wallet)
    };
    assert_eq!(
        check_with(&fixtures::maker_preparation(), &lighter, None).unwrap_err().kind,
        VerificationKind::Unsupported
    );
}

fn close(items: &Value, ids: &[&str]) -> Result<Verified, VerificationError> {
    let ids: Vec<OrderId> = ids.iter().map(|id| id.parse().unwrap()).collect();
    check_close_orders(
        &fixtures::to_sign(items),
        &ids,
        OWNER,
        EscrowEnvironment::Production,
        fixtures::now(),
    )
}

#[test]
fn a_close_names_only_asked_orders_of_the_master_within_the_hour() {
    let both = [POOL, "0x5555555555555555555555555555555555555555555555555555555555555555"];
    let verified = close(&fixtures::close_items(), &both).unwrap();
    assert_eq!(verified.not_after(), Some(NOW + 3570));
    let message = |name: &str, value: Value| {
        edited(fixtures::close_items(), |items| {
            items[0]["typed_data"]["message"][name] = value.clone();
        })
    };
    let cases = [
        (message("account", json!(OTHER)), details::ACCOUNT),
        (message("orders", json!([])), details::ORDERS),
        (message("orders", json!([POOL, POOL])), details::ORDERS),
        (message("orders", json!([testing::ORDER])), details::ORDERS),
        (message("deadline", json!((NOW + 3631).to_string())), details::DEADLINE),
        (
            edited(fixtures::close_items(), |items| items[0]["signer"] = json!(OTHER)),
            details::TO_SIGN_SIGNER,
        ),
        (edited(fixtures::close_items(), |items| items[0]["kind"] = json!("fund")), details::KIND),
        (
            edited(fixtures::close_items(), |items| {
                items[0]["typed_data"]["domain"]["chainId"] = json!(137);
            }),
            details::DOMAIN,
        ),
    ];
    for (index, (items, detail)) in cases.iter().enumerate() {
        assert_eq!(close(items, &both).unwrap_err().detail, *detail, "case {index}");
    }
    assert_eq!(close(&fixtures::close_items(), &[POOL]).unwrap_err().detail, details::ORDERS);
    let two = edited(fixtures::close_items(), |items| {
        let item = items[0].clone();
        items.as_array_mut().unwrap().push(item);
    });
    assert_eq!(close(&two, &both).unwrap_err().detail, details::TO_SIGN);
}

fn pool_order() -> Order {
    let mut pool = fixtures::pool();
    pool["last_sequence"] = json!(11);
    fixtures::model(&pool)
}

/// The vector's quote set for [`POOL`], as the maker asked it.
fn quote_item() -> Value {
    let mut typed = testing::sample("quote_set");
    typed["message"]["owner"] = json!(OWNER);
    json!({"kind": "quote_set", "signer": MAKER, "typed_data": typed})
}

fn quote_terms() -> Vec<QuoteTerms> {
    ["polymarket", "gmx"]
        .into_iter()
        .map(|venue| QuoteTerms {
            venue: venue.parse().unwrap(),
            recipient: OWNER,
            supply: U256::from(500_000_000u64),
            receive: U256::from(500_250_000u64),
            min_fill: U256::from(10_000_000u64),
        })
        .collect()
}

fn signed_quote(item: &Value, requested: &[QuoteTerms]) -> Result<Verified, VerificationError> {
    let item: ToSign = fixtures::model(item);
    check_signed_quote(
        &item,
        &pool_order(),
        requested,
        12,
        1_790_000_000,
        1_790_003_601,
        EscrowEnvironment::Production,
    )
}

/// `protocol.ts` `checkSignedQuote`: the entire set, in order, each quote as asked.
#[test]
fn a_quote_set_is_exactly_the_asked_quotes_in_order() {
    assert!(signed_quote(&quote_item(), &quote_terms()).is_ok());
    let quote = |index: usize, name: &str, value: Value| {
        edited(quote_item(), |item| {
            item["typed_data"]["message"]["quotes"][index][name] = value.clone();
        })
    };
    let cases = [
        (quote(1, "venue", json!("polymarket")), details::QUOTES_VENUE),
        (quote(1, "chainId", json!(137)), details::QUOTES_CHAIN_ID),
        (quote(1, "token", json!(OTHER)), details::QUOTES_TOKEN),
        (quote(1, "recipient", json!(OTHER)), details::QUOTES_RECIPIENT),
        (quote(1, "supply", json!("500000001")), details::QUOTES_SUPPLY),
        (quote(1, "receive", json!("1")), details::QUOTES_RECEIVE),
        (quote(1, "minFill", json!("1")), details::QUOTES_MIN_FILL),
    ];
    for (prepared, detail) in &cases {
        let error = signed_quote(prepared, &quote_terms()).unwrap_err();
        assert_eq!((error.detail, error.index), (*detail, Some(1)));
    }
    let message = |name: &str, value: Value| {
        edited(quote_item(), |item| item["typed_data"]["message"][name] = value.clone())
    };
    let cases = [
        (message("owner", json!(OTHER)), details::OWNER),
        (message("offerId", json!(testing::ORDER)), details::OFFER_ID),
        (message("sequence", json!(13)), details::SEQUENCE),
        (message("expiresAt", json!(1_790_003_602)), details::EXPIRES_AT),
        (message("quotes", json!([])), details::QUOTES),
        (edited(quote_item(), |item| item["signer"] = json!(OWNER)), details::TO_SIGN_SIGNER),
        (edited(quote_item(), |item| item["kind"] = json!("fund")), details::KIND),
    ];
    for (index, (prepared, detail)) in cases.iter().enumerate() {
        assert_eq!(
            signed_quote(prepared, &quote_terms()).unwrap_err().detail,
            *detail,
            "case {index}"
        );
    }
    let mut reversed = quote_terms();
    reversed.reverse();
    assert_eq!(signed_quote(&quote_item(), &reversed).unwrap_err().detail, details::QUOTES_VENUE);
    assert_eq!(
        signed_quote(&quote_item(), &quote_terms()[..1]).unwrap_err().detail,
        details::QUOTES
    );
    assert_eq!(signed_quote(&quote_item(), &[]).unwrap_err().detail, details::QUOTES);
    // A quote never receives on the pool's own venue, nor on a venue this release lacks.
    let mut own = quote_terms();
    own[0].venue = VenueId::Hyperliquid;
    let own_item = quote(0, "venue", json!("hyperliquid"));
    assert_eq!(signed_quote(&own_item, &own).unwrap_err().detail, details::QUOTES_VENUE);
    let zero = quote_terms()
        .into_iter()
        .map(|terms| QuoteTerms { supply: U256::ZERO, min_fill: U256::ZERO, ..terms })
        .collect::<Vec<_>>();
    let zero_item = edited(quote_item(), |item| {
        for quote in item["typed_data"]["message"]["quotes"].as_array_mut().unwrap() {
            quote["supply"] = json!("0");
            quote["minFill"] = json!("0");
        }
    });
    assert_eq!(signed_quote(&zero_item, &zero).unwrap_err().detail, details::QUOTES_SUPPLY);
}

#[test]
fn a_created_credential_echoes_the_signer_and_scopes_asked() {
    let created: CredentialCreated = serde_json::from_value(fixture("credential_created")).unwrap();
    let scopes = created.scopes.clone();
    assert!(check_created_credential(&created, created.quote_signer, &scopes).is_ok());
    let error = check_created_credential(&created, OTHER, &scopes).unwrap_err();
    assert_eq!(error.detail, details::CREDENTIAL_QUOTE_SIGNER);
    let error = check_created_credential(&created, created.quote_signer, &scopes[1..]).unwrap_err();
    assert_eq!(error.detail, details::CREDENTIAL_SCOPES);
}