lamarge 0.6.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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
//! Direct transfers against a stateful mock of `/v1/direct`, ported from
//! `sdk-ts/src/direct.test.ts` (each test names its source): what is asked of the sender, in which
//! order, and never twice.

use std::sync::{Arc, Mutex};

use alloy_primitives::address;
use alloy_sol_types::{SolCall, sol};
use chrono::{DateTime, Utc};
use serde_json::{Value, json};
use wiremock::{Mock, Request, ResponseTemplate, matchers::path_regex};

use super::*;
use crate::{
    SendFuture, StatusFuture,
    error::{VerificationError, VerificationKind},
    flows::conversion::{
        LEAST_CONVERTED, POLYGON_FUNDING_CONVERTER, POLYGON_USDC, conversion_minimum,
    },
    testing::{NOW, at, harness::*, time},
    types::{ClientId, EscrowEnvironment},
};

sol! {
    function approve(address spender, uint256 amount);
    function directDeposit(
        address recipient,
        address token,
        uint256 amount,
        uint256 minOut,
        uint256 nonce,
        uint256 deadline
    );
    function convertDeposit(uint256 amountIn, uint256 minOut, uint256 nonce, uint256 deadline);
}

const OPERATION: &str = "0192f1c2-3d4e-7f00-8a1b-2c3d4e5f6a70";
const RECIPIENT: Address = address!("3333333333333333333333333333333333333333");
const HASH: B256 = B256::repeat_byte(0x22);
const AMOUNT: u64 = 10_000_000;
const CONVERTED: u64 = 9_995_000;
const NONCE: u64 = 42;

fn amount(units: u64) -> Amount {
    Amount::new(U256::from(units))
}

fn deadline() -> u64 {
    NOW.unsigned_abs() + 1_800
}

fn now() -> DateTime<Utc> {
    at(0)
}

/// What the server holds of the operation and the owner's funds.
struct Api {
    venues: Value,
    operation: Option<Value>,
    /// Merged into every operation answered.
    patch: Value,
    allowance: U256,
    /// The fence moves the operation to pending, and its answer is lost.
    lose_fence: bool,
    /// When the funds were read; now by default.
    observed_at: Option<String>,
}

impl Api {
    fn answer(&self) -> Value {
        let mut operation = self.operation.clone().unwrap();
        for (field, value) in self.patch.as_object().unwrap() {
            operation[field] = value.clone();
        }
        operation
    }

    fn handle(&mut self, request: &Request) -> ResponseTemplate {
        let path = request.url.path().to_owned();
        let body: Value = serde_json::from_slice(&request.body).unwrap_or(Value::Null);
        match (request.method.as_str(), path.as_str()) {
            ("GET", "/v1/venues") => ok(self.venues.clone()),
            ("POST", "/v1/direct") => {
                if self.operation.is_none() {
                    self.operation = Some(created(&body));
                }
                ok(self.answer())
            }
            ("GET", route) if route.ends_with("/funding") => {
                let operation = self.answer();
                ok(json!({
                    "owner": operation["owner"], "token": operation["token"],
                    "spender": operation["escrow"], "balance": operation["amount"],
                    "allowance": self.allowance.to_string(), "block": 1,
                    "observed_at": self.observed_at.clone().unwrap_or_else(|| time(0)),
                }))
            }
            ("GET", _) => ok(self.answer()),
            _ => self.report(&body),
        }
    }

    /// A hash joins the attempts; an empty report fences a prepared operation.
    fn report(&mut self, body: &Value) -> ResponseTemplate {
        let operation = self.operation.as_mut().unwrap();
        if let Some(hash) = body.get("tx_hash") {
            operation["attempts"].as_array_mut().unwrap().push(hash.clone());
        } else {
            if operation["state"] != "prepared" {
                return api_error(409, "STATE_CONFLICT");
            }
            operation["state"] = json!("pending");
            if self.lose_fence {
                return ResponseTemplate::new(503);
            }
        }
        ok(self.answer())
    }
}

/// The operation the server creates for `request`.
fn created(request: &Value) -> Value {
    let venue: VenueId = serde_json::from_value(request["venue"].clone()).unwrap();
    let chain = deployments::chain(&venue).unwrap();
    let mut operation = request.clone();
    for (field, value) in [
        ("id", json!(OPERATION)),
        ("move_id", request.get("move_id").cloned().unwrap_or(Value::Null)),
        ("chain_id", json!(chain.id)),
        ("escrow", json!(deployments::contract(&venue, EscrowEnvironment::Production))),
        ("nonce", json!(NONCE.to_string())),
        ("deadline", json!(deadline().to_string())),
        ("state", json!("prepared")),
        ("attempts", json!([])),
        ("tx_hash", Value::Null),
        ("received", Value::Null),
    ] {
        operation[field] = value;
    }
    operation
}

/// Production's venues, Polymarket and GMX taking direct deposits and withdrawals when `enabled`,
/// Polymarket advertising its conversion.
fn direct_venues(enabled: bool) -> Value {
    let mut venues = venues(EscrowEnvironment::Production);
    for venue in venues.as_array_mut().unwrap() {
        if venue["id"] == "polymarket" || venue["id"] == "gmx" {
            venue["chain"]["direct_deposit"] = json!(enabled);
            venue["chain"]["direct_withdrawal"] = json!(enabled);
        }
        if venue["id"] == "polymarket" {
            venue["chain"]["wallet_funding"]["conversion"] = json!({
                "token": POLYGON_USDC, "symbol": "USDC", "decimals": 6,
                "converter": POLYGON_FUNDING_CONVERTER, "min_out_bps": 9_995, "minimum": "10000",
            });
        }
    }
    venues
}

/// The owner's wallet: what it was asked; an `approve` raises the allowance.
#[derive(Default)]
struct Wallet {
    sent: Mutex<Vec<Transaction>>,
    declined: Mutex<bool>,
    lose_hash: Mutex<bool>,
    /// An `approve` of unknown outcome, raising no allowance.
    lose_approval: Mutex<bool>,
    /// What `status` answers; `Unknown` by default.
    status: Mutex<Option<SendStatus>>,
    api: Mutex<Option<Arc<Mutex<Api>>>>,
}

impl TransactionSender for Wallet {
    fn send(&self, transaction: Transaction) -> SendFuture<'_> {
        Box::pin(async move {
            self.sent.lock().unwrap().push(transaction.clone());
            if *self.declined.lock().unwrap() {
                return Err(SendError::NotSent("declined".into()));
            }
            let api = self.api.lock().unwrap().clone().unwrap();
            let token: Address =
                serde_json::from_value(api.lock().unwrap().answer()["token"].clone()).unwrap();
            if transaction.to == token {
                if *self.lose_approval.lock().unwrap() {
                    return Err(SendError::Unknown("lost approval".into()));
                }
                api.lock().unwrap().allowance = U256::from(AMOUNT);
            } else if *self.lose_hash.lock().unwrap() {
                return Err(SendError::Unknown("lost hash".into()));
            }
            Ok(HASH)
        })
    }

    fn status<'a>(&'a self, _: &'a str) -> StatusFuture<'a> {
        let status = self.status.lock().unwrap().unwrap_or(SendStatus::Unknown);
        Box::pin(async move { Ok(status) })
    }
}

struct Scenario {
    harness: Harness,
    api: Arc<Mutex<Api>>,
    wallet: Wallet,
    request: DirectRequest,
    session: Session,
}

impl Scenario {
    async fn new(request: impl FnOnce(Address) -> DirectRequest) -> Self {
        let harness = Harness::bare().await;
        let api = Arc::new(Mutex::new(Api {
            venues: direct_venues(true),
            operation: None,
            patch: json!({}),
            allowance: U256::ZERO,
            lose_fence: false,
            observed_at: None,
        }));
        let state = Arc::clone(&api);
        Mock::given(path_regex(r"^/v1/(venues|direct)"))
            .respond_with(move |request: &Request| state.lock().unwrap().handle(request))
            .mount(&harness.server)
            .await;
        harness.serve_sign_in().await;
        let session = harness.session().await;
        let request = request(harness.address());
        let wallet = Wallet::default();
        *wallet.api.lock().unwrap() = Some(Arc::clone(&api));
        Self { harness, api, wallet, request, session }
    }

    /// A deposit of ten units into Polymarket for `recipient`: pUSD, or native USDC converted.
    async fn deposit(native: bool, recipient: Option<Address>) -> Self {
        Self::new(|owner| {
            let (token, min_out) =
                if native { (POLYGON_USDC, CONVERTED) } else { (POLYMARKET_TOKEN, AMOUNT) };
            let id = ClientId::new("direct-1").unwrap();
            let venue = VenueId::Polymarket;
            let recipient = recipient.unwrap_or(owner);
            let (amount, min_out) = (amount(AMOUNT), amount(min_out));
            DirectRequest::deposit(id, venue, owner, recipient, token, amount, min_out).unwrap()
        })
        .await
    }

    async fn withdrawal() -> Self {
        Self::new(|owner| {
            let id = ClientId::new("direct-1").unwrap();
            DirectRequest::gmx_withdrawal(id, owner, deployments::GMX.token, amount(AMOUNT))
        })
        .await
    }

    /// A run with the scenario's journal.
    async fn run(&self) -> Result<DirectOutcome> {
        self.session.direct_transfer(&self.request, &self.wallet).await
    }

    /// A run from another device: a fresh journal.
    async fn elsewhere(&self) -> Result<DirectOutcome> {
        self.harness.session().await.direct_transfer(&self.request, &self.wallet).await
    }

    fn edit(&self, edit: impl FnOnce(&mut Api)) {
        edit(&mut self.api.lock().unwrap());
    }

    fn sent(&self) -> Vec<Transaction> {
        self.wallet.sent.lock().unwrap().clone()
    }

    fn escrow(&self) -> Address {
        deployments::contract(&self.request.venue, EscrowEnvironment::Production).unwrap()
    }

    fn confirm(&self) {
        self.edit(|api| {
            let operation = api.operation.as_mut().unwrap();
            operation["state"] = json!("confirmed");
            operation["tx_hash"] = json!(HASH);
            operation["received"] = operation["min_out"].clone();
        });
    }

    async fn fences(&self) -> usize {
        let bodies = self.harness.bodies("POST", &format!("/v1/direct/{OPERATION}")).await;
        bodies.iter().filter(|body| body.get("tx_hash").is_none()).count()
    }
}

const POLYMARKET_TOKEN: Address = deployments::POLYMARKET.token;

fn state(outcome: Result<DirectOutcome>) -> DirectState {
    match outcome.unwrap() {
        DirectOutcome::Operation(operation) => operation.state,
        DirectOutcome::Waiting(wait) => panic!("waiting: {wait:?}"),
    }
}

fn refusal(outcome: Result<DirectOutcome>) -> VerificationError {
    let Error::Verification(error) = outcome.unwrap_err() else { panic!("refused") };
    error
}

fn inspected(
    transaction: &Transaction,
    owner: Address,
    recipient: Address,
) -> Result<DirectInspection> {
    let (chain_id, to, data) = (transaction.chain_id, transaction.to, &transaction.data);
    inspect_direct_transaction(chain_id, to, data, owner, recipient, now())
}

/// "direct deposit calldata fixes the recipient, token, amount, minimum and nonce", of pUSD and
/// of native USDC: an `approve` of the escrow, then its `directDeposit`; once confirmed, nothing
/// is asked again.
#[tokio::test]
async fn a_deposit_approves_then_sends_the_deposit_of_its_terms() {
    for native in [false, true] {
        let s = Scenario::deposit(native, Some(RECIPIENT)).await;
        assert_eq!(state(s.run().await), DirectState::Pending);
        let [approval, deposit] = s.sent().try_into().unwrap();
        let escrow = s.escrow();
        assert_eq!((approval.chain_id, approval.to), (137, s.request.token));
        let allowance = approveCall { spender: escrow, amount: U256::from(AMOUNT) };
        assert_eq!(approval.data, allowance.abi_encode());
        assert_eq!((deposit.chain_id, deposit.to), (137, escrow));
        let expected = directDepositCall {
            recipient: RECIPIENT,
            token: s.request.token,
            amount: U256::from(AMOUNT),
            minOut: s.request.min_out.get(),
            nonce: U256::from(NONCE),
            deadline: U256::from(deadline()),
        };
        assert_eq!(deposit.data, expected.abi_encode());
        assert_eq!(approval.id, format!("lamarge.direct.{OPERATION}.approve"));
        assert_eq!(deposit.id, format!("lamarge.direct.{OPERATION}.deposit"));

        s.confirm();
        assert_eq!(state(s.run().await), DirectState::Confirmed);
        assert_eq!(s.sent().len(), 2);
    }
}

/// "an existing unlimited maker allowance is preserved".
#[tokio::test]
async fn an_existing_allowance_sends_the_deposit_alone() {
    let s = Scenario::deposit(false, Some(RECIPIENT)).await;
    s.edit(|api| api.allowance = U256::MAX);
    s.run().await.unwrap();
    let [deposit] = s.sent().try_into().unwrap();
    assert_eq!(deposit.to, s.escrow());
}

/// "losing the fence never resends from the same or another device".
#[tokio::test]
async fn a_lost_fence_never_sends_from_the_same_or_another_device() {
    let s = Scenario::deposit(false, Some(RECIPIENT)).await;
    s.edit(|api| {
        api.allowance = U256::MAX;
        api.lose_fence = true;
    });
    assert!(s.run().await.is_err());
    assert_eq!(state(s.run().await), DirectState::Pending);
    assert_eq!(state(s.elsewhere().await), DirectState::Pending);
    assert!(s.sent().is_empty());
    s.confirm();
    s.edit(|api| api.venues = direct_venues(false));
    assert_eq!(state(s.elsewhere().await), DirectState::Confirmed);
}

/// "losing the hash never resends from the same or another device".
#[tokio::test]
async fn a_lost_hash_never_sends_again_from_the_same_or_another_device() {
    let s = Scenario::deposit(false, Some(RECIPIENT)).await;
    s.edit(|api| api.allowance = U256::MAX);
    *s.wallet.lose_hash.lock().unwrap() = true;
    assert_eq!(s.run().await.unwrap(), DirectOutcome::Waiting(DirectWait::Unknown));
    assert_eq!(state(s.run().await), DirectState::Pending);
    assert_eq!(state(s.elsewhere().await), DirectState::Pending);
    assert_eq!(s.sent().len(), 1);
    s.confirm();
    s.edit(|api| api.venues = direct_venues(false));
    assert_eq!(state(s.elsewhere().await), DirectState::Confirmed);
}

/// "a changed recipient, token, amount or chain is rejected before approval".
#[tokio::test]
async fn changed_terms_are_refused_before_any_transaction() {
    let owner = json!(address!("4444444444444444444444444444444444444444"));
    for patch in [
        json!({"recipient": owner}),
        json!({"amount": "10000001"}),
        json!({"token": owner}),
        json!({"chain_id": 999}),
        json!({"escrow": owner}),
    ] {
        let s = Scenario::deposit(false, Some(RECIPIENT)).await;
        s.edit(|api| api.patch = patch);
        assert_eq!(refusal(s.run().await).detail, details::DIRECT);
        assert!(s.sent().is_empty());
    }
}

/// "a missing capability never requests a signature or transaction".
#[tokio::test]
async fn a_missing_capability_sends_nothing() {
    let s = Scenario::deposit(false, Some(RECIPIENT)).await;
    s.edit(|api| api.venues = direct_venues(false));
    let error = refusal(s.run().await);
    assert_eq!((error.kind, error.detail), (VerificationKind::Unsupported, details::VENUE));
    assert!(s.sent().is_empty());
}

/// A native USDC deposit needs Polygon's advertised conversion to be the pinned one.
#[tokio::test]
async fn a_native_deposit_without_the_pinned_conversion_sends_nothing() {
    let s = Scenario::deposit(true, Some(RECIPIENT)).await;
    s.edit(|api| {
        for venue in api.venues.as_array_mut().unwrap() {
            if venue["id"] == "polymarket" {
                venue["chain"]["wallet_funding"]["conversion"]["converter"] = json!(RECIPIENT);
            }
        }
    });
    let error = refusal(s.run().await);
    assert_eq!((error.kind, error.detail), (VerificationKind::Differs, details::WALLET_FUNDING));
    assert!(s.sent().is_empty());
}

/// "GMX withdrawal is one owner-sent transferOut and never a maker route".
#[tokio::test]
async fn a_gmx_withdrawal_is_one_transfer_out() {
    let s = Scenario::withdrawal().await;
    s.run().await.unwrap();
    let [transfer_out] = s.sent().try_into().unwrap();
    assert_eq!((transfer_out.chain_id, transfer_out.to), (42_161, gmx::TRANSFER_ROUTER));
    assert!(transfer_out.data.starts_with(&[0x0b, 0x90, 0x66, 0xd9]));
    assert_eq!(transfer_out.id, format!("lamarge.direct.{OPERATION}.withdrawal"));
    let received = s.harness.server.received_requests().await.unwrap();
    assert!(received.iter().all(|request| {
        let path = request.url.path();
        !["takes", "routes", "quotes"].iter().any(|route| path.contains(route))
    }));
    s.run().await.unwrap();
    assert_eq!(s.sent().len(), 1);
}

/// "an explicit deposit refusal can retry only the same persisted operation": the same
/// transaction, fenced once.
#[tokio::test]
async fn a_declined_deposit_is_asked_again_under_its_fence() {
    let s = Scenario::deposit(false, Some(RECIPIENT)).await;
    s.edit(|api| api.allowance = U256::MAX);
    *s.wallet.declined.lock().unwrap() = true;
    assert_eq!(s.run().await.unwrap(), DirectOutcome::Waiting(DirectWait::NotSent));
    *s.wallet.declined.lock().unwrap() = false;
    s.run().await.unwrap();
    let [first, second] = s.sent().try_into().unwrap();
    assert_eq!(first, second);
    assert_eq!(s.fences().await, 1);
}

/// A declined `approve` is asked again by the next run, the deposit only once approved.
#[tokio::test]
async fn a_declined_approval_is_asked_again() {
    let s = Scenario::deposit(false, Some(RECIPIENT)).await;
    *s.wallet.declined.lock().unwrap() = true;
    assert_eq!(s.run().await.unwrap(), DirectOutcome::Waiting(DirectWait::NotSent));
    assert_eq!(s.fences().await, 0);
    *s.wallet.declined.lock().unwrap() = false;
    s.run().await.unwrap();
    let [declined, approval, deposit] = s.sent().try_into().unwrap();
    assert_eq!(declined, approval);
    assert_eq!(deposit.to, s.escrow());
}

/// A fenced deposit the sender then says it never sent is asked again: the same transaction,
/// under its first fence.
#[tokio::test]
async fn a_fenced_deposit_the_sender_never_sent_is_asked_again_unfenced() {
    let s = Scenario::deposit(false, Some(RECIPIENT)).await;
    s.edit(|api| api.allowance = U256::MAX);
    *s.wallet.lose_hash.lock().unwrap() = true;
    assert_eq!(s.run().await.unwrap(), DirectOutcome::Waiting(DirectWait::Unknown));
    *s.wallet.lose_hash.lock().unwrap() = false;
    *s.wallet.status.lock().unwrap() = Some(SendStatus::NotSent);
    s.run().await.unwrap();
    let [first, second] = s.sent().try_into().unwrap();
    assert_eq!(first, second);
    assert_eq!(s.fences().await, 1);
}

/// A hash the sender knows on resume is reported when the operation's attempts miss it, and
/// nothing is sent again.
#[tokio::test]
async fn a_hash_found_on_resume_is_reported() {
    let s = Scenario::deposit(false, Some(RECIPIENT)).await;
    s.edit(|api| api.allowance = U256::MAX);
    *s.wallet.lose_hash.lock().unwrap() = true;
    s.run().await.unwrap();
    let found = B256::repeat_byte(0x33);
    *s.wallet.status.lock().unwrap() = Some(SendStatus::Sent(found));
    assert_eq!(state(s.run().await), DirectState::Pending);
    let reports = s.harness.bodies("POST", &format!("/v1/direct/{OPERATION}")).await;
    assert_eq!(reports, vec![json!({}), json!({"tx_hash": found})]);
    assert_eq!(s.sent().len(), 1);
}

/// "A GMX withdrawal has no application nonce; only its first fenced prompt may send it": not
/// even once the sender says it never sent it.
#[tokio::test]
async fn a_fenced_gmx_withdrawal_the_sender_never_sent_is_not_asked_again() {
    let s = Scenario::withdrawal().await;
    *s.wallet.lose_hash.lock().unwrap() = true;
    assert_eq!(s.run().await.unwrap(), DirectOutcome::Waiting(DirectWait::Unknown));
    *s.wallet.lose_hash.lock().unwrap() = false;
    *s.wallet.status.lock().unwrap() = Some(SendStatus::NotSent);
    assert_eq!(state(s.run().await), DirectState::Pending);
    assert_eq!(state(s.run().await), DirectState::Pending);
    assert_eq!(s.sent().len(), 1);
}

/// An `approve` of unknown outcome is waited for; once the sender says it never sent it, it is
/// asked again, then the deposit.
#[tokio::test]
async fn an_approval_the_sender_never_sent_is_asked_again() {
    let s = Scenario::deposit(false, Some(RECIPIENT)).await;
    *s.wallet.lose_approval.lock().unwrap() = true;
    assert_eq!(s.run().await.unwrap(), DirectOutcome::Waiting(DirectWait::Approval));
    assert_eq!(s.run().await.unwrap(), DirectOutcome::Waiting(DirectWait::Approval));
    assert_eq!(s.sent().len(), 1, "unknown: not asked again");
    *s.wallet.lose_approval.lock().unwrap() = false;
    *s.wallet.status.lock().unwrap() = Some(SendStatus::NotSent);
    s.run().await.unwrap();
    let [lost, approval, deposit] = s.sent().try_into().unwrap();
    assert_eq!(lost, approval);
    assert_eq!(deposit.to, s.escrow());
}

/// Funds read more than 15 s ahead of the client's clock are stale, to the millisecond.
#[tokio::test]
async fn funds_read_past_fifteen_seconds_ahead_are_refused() {
    let s = Scenario::deposit(false, Some(RECIPIENT)).await;
    s.edit(|api| {
        api.allowance = U256::MAX;
        api.observed_at = Some(
            (now() + chrono::TimeDelta::milliseconds(15_001))
                .to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
        );
    });
    let error = refusal(s.run().await);
    assert_eq!((error.kind, error.detail), (VerificationKind::Changed, details::DIRECT_FUNDING));
    assert!(s.sent().is_empty());
}

/// A request read back from storage is checked as `deposit` checks it, before any call.
#[tokio::test]
async fn a_stored_request_is_checked_before_any_call() {
    let s = Scenario::deposit(false, Some(RECIPIENT)).await;
    let mut stored = serde_json::to_value(&s.request).unwrap();
    stored["venue"] = json!("lighter");
    let request: DirectRequest = serde_json::from_value(stored).unwrap();
    let refused = s.session.direct_transfer(&request, &s.wallet).await;
    assert!(matches!(refused, Err(Error::InvalidRequest(_))));
    assert!(s.harness.requests("POST", "/v1/direct").await.is_empty());
}

/// "isolated signers accept only canonical own-account direct calls".
#[tokio::test]
async fn inspection_accepts_only_canonical_own_account_calls() {
    let s = Scenario::deposit(false, None).await;
    let owner = s.harness.address();
    s.run().await.unwrap();
    let sent = s.sent();
    for transaction in &sent {
        assert_eq!(inspected(transaction, owner, owner).unwrap().amount, amount(AMOUNT));
    }
    let deposit = &sent[1];
    let mut longer = deposit.clone();
    longer.data.push(0);
    let mut elsewhere = deposit.clone();
    elsewhere.to = RECIPIENT;
    let mut chain = deposit.clone();
    chain.chain_id = 999;
    for changed in [longer, elsewhere, chain] {
        assert!(inspected(&changed, owner, owner).is_err());
    }
    assert!(inspected(deposit, RECIPIENT, RECIPIENT).is_err());
    let (chain_id, to, data) = (deposit.chain_id, deposit.to, &deposit.data);
    let late = at(1_801);
    assert!(inspect_direct_transaction(chain_id, to, data, owner, owner, late).is_err());

    let g = Scenario::withdrawal().await;
    g.run().await.unwrap();
    let owner = g.harness.address();
    let inspection = inspected(&g.sent()[0], owner, owner).unwrap();
    assert_eq!(inspection.step, DirectStep::Withdrawal);
}

/// "isolated signers accept a deposit to the request's recipient and refuse another".
#[tokio::test]
async fn inspection_binds_the_deposit_to_the_requests_recipient() {
    let s = Scenario::deposit(false, Some(RECIPIENT)).await;
    let owner = s.harness.address();
    s.run().await.unwrap();
    let sent = s.sent();
    let deposit = &sent[1];
    let inspection = inspected(deposit, owner, RECIPIENT).unwrap();
    assert_eq!(
        (inspection.step, inspection.recipient, inspection.amount),
        (DirectStep::Deposit, RECIPIENT, amount(AMOUNT))
    );
    assert_eq!(inspected(deposit, owner, owner).unwrap_err().to_string(), refused_recipient());
    let mut tampered = deposit.clone();
    tampered.data[16..36].copy_from_slice(&[0x44; 20]);
    assert_eq!(
        inspected(&tampered, owner, RECIPIENT).unwrap_err().to_string(),
        refused_recipient()
    );
}

fn refused_recipient() -> String {
    Error::from(differs(details::DIRECT_RECIPIENT)).to_string()
}

/// "wallet funding conversion inspection binds Polygon, token, floor, deployment and deadline".
#[test]
fn inspection_binds_a_conversion_to_polygon_its_floor_escrow_and_deadline() {
    let escrow = deployments::escrow(137, EscrowEnvironment::Production).unwrap();
    let owner = address!("1111111111111111111111111111111111111111");
    let data = convertDepositCall {
        amountIn: U256::from(AMOUNT),
        minOut: U256::from(CONVERTED),
        nonce: U256::from(NONCE),
        deadline: U256::from(deadline()),
    }
    .abi_encode();
    let inspection = inspect_direct_transaction(137, escrow, &data, owner, owner, now()).unwrap();
    assert_eq!(
        (inspection.step, inspection.token, inspection.amount, inspection.minimum),
        (DirectStep::Convert, POLYGON_USDC, amount(AMOUNT), amount(CONVERTED))
    );
    let mut longer = data.clone();
    longer.push(0);
    assert!(inspect_direct_transaction(137, RECIPIENT, &data, owner, owner, now()).is_err());
    assert!(inspect_direct_transaction(999, escrow, &data, owner, owner, now()).is_err());
    assert!(inspect_direct_transaction(137, escrow, &longer, owner, owner, now()).is_err());
    let late = at(1_801);
    assert!(inspect_direct_transaction(137, escrow, &data, owner, owner, late).is_err());
    let floor = convertDepositCall {
        amountIn: U256::from(AMOUNT),
        minOut: U256::from(CONVERTED - 1),
        nonce: U256::from(NONCE),
        deadline: U256::from(deadline()),
    }
    .abi_encode();
    assert!(inspect_direct_transaction(137, escrow, &floor, owner, owner, now()).is_err());
}

/// "a direct prompt cannot switch to another pinned deployment between preparation and
/// capability read".
#[tokio::test]
async fn another_pinned_escrow_advertised_sends_nothing() {
    let s = Scenario::deposit(false, Some(RECIPIENT)).await;
    let development = deployments::contract(&VenueId::Polymarket, EscrowEnvironment::Development);
    s.edit(|api| {
        for venue in api.venues.as_array_mut().unwrap() {
            if venue["id"] == "polymarket" {
                venue["chain"]["escrow"] = json!(development);
            }
        }
    });
    let error = refusal(s.run().await);
    assert_eq!((error.kind, error.detail), (VerificationKind::Differs, details::ESCROW));
    assert!(s.sent().is_empty());
}

/// `checkDirectAmounts`: the venue's own token whole; Polygon native USDC only into Polymarket,
/// at least one cent and its conversion floor.
#[test]
fn direct_amounts_follow_the_token_and_the_conversion_floor() {
    let check = |venue: &VenueId, token, amount_in: u64, minimum: u64, deposit| {
        inspect::amounts(venue, token, amount(amount_in), amount(minimum), deposit)
            .map_err(|e| e.detail)
    };
    let polymarket = &VenueId::Polymarket;
    assert_eq!(check(polymarket, POLYMARKET_TOKEN, AMOUNT, AMOUNT, true), Ok(()));
    assert_eq!(check(&VenueId::Gmx, deployments::GMX.token, AMOUNT, AMOUNT, false), Ok(()));
    assert_eq!(
        check(polymarket, POLYMARKET_TOKEN, AMOUNT, AMOUNT - 1, true),
        Err(details::DIRECT_AMOUNT)
    );
    assert_eq!(check(polymarket, POLYMARKET_TOKEN, 0, 0, true), Err(details::DIRECT_AMOUNT));
    assert_eq!(check(polymarket, POLYGON_USDC, AMOUNT, CONVERTED, true), Ok(()));
    assert_eq!(
        check(polymarket, POLYGON_USDC, AMOUNT, CONVERTED - 1, true),
        Err(details::DIRECT_AMOUNT)
    );
    let least = LEAST_CONVERTED;
    assert_eq!(check(polymarket, POLYGON_USDC, least, least - 5, true), Ok(()));
    assert_eq!(check(polymarket, POLYGON_USDC, least - 1, 1, true), Err(details::DIRECT_AMOUNT));
    assert_eq!(
        check(polymarket, POLYGON_USDC, AMOUNT, CONVERTED, false),
        Err(details::DIRECT_TOKEN)
    );
    let hyperliquid = &VenueId::Hyperliquid;
    assert_eq!(
        check(hyperliquid, POLYGON_USDC, AMOUNT, CONVERTED, true),
        Err(details::DIRECT_TOKEN)
    );
    let unknown: VenueId = "other".parse().unwrap();
    assert_eq!(check(&unknown, POLYGON_USDC, AMOUNT, AMOUNT, true), Err(details::VENUE));
}

/// A deposit request is refused before any call into a venue settled inside itself, or with
/// amounts the escrow refuses.
#[test]
fn a_deposit_request_is_checked_when_made() {
    let id = || ClientId::new("direct-1").unwrap();
    let owner = address!("1111111111111111111111111111111111111111");
    let deposit = |venue: VenueId, token, min_out: u64| {
        DirectRequest::deposit(id(), venue, owner, owner, token, amount(AMOUNT), amount(min_out))
    };
    assert!(deposit(VenueId::Polymarket, POLYGON_USDC, CONVERTED).is_ok());
    assert!(deposit(VenueId::Hyperliquid, deployments::HYPERLIQUID.token, AMOUNT).is_ok());
    for refused in [
        deposit(VenueId::Lighter, deployments::LIGHTER.token, AMOUNT),
        deposit(VenueId::Gmx, POLYGON_USDC, CONVERTED),
        deposit(VenueId::Polymarket, POLYMARKET_TOKEN, CONVERTED),
    ] {
        assert!(matches!(refused, Err(Error::InvalidRequest(_))));
    }
}

/// `conversionMinimum` and the pinned Polygon tokens.
#[test]
fn the_conversion_floor_rounds_up_and_the_tokens_are_the_pins() {
    assert_eq!(conversion_minimum(amount(AMOUNT)), Some(amount(CONVERTED)));
    assert_eq!(conversion_minimum(amount(1)), Some(amount(1)));
    assert_eq!(conversion_minimum(Amount::new(U256::MAX)), None);
    assert_eq!(Some(POLYGON_USDC), deployments::POLYMARKET.wallet_token);
    assert_eq!(POLYGON_FUNDING_CONVERTER, address!("2d31ff03f5da1c385a64d764389962c160e789f8"));
}