o2-tools 0.4.7-rc5

Reusable tooling for trade account and order book contract interactions on Fuel
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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
//! The prop-account surface: session keys, cosignatures, parenthood and the
//! three callbacks the pool drives.
//!
//! Every test here runs against the SAME fixture the pool tests use, so a
//! rule proven here is proven on the account a real session actually trades
//! through. The pool's own guards live in `prop_pool_guard_tests`.

use super::*;
use crate::prop::{
    MarginTradeAccountWithdrawn,
    ParallelRevokeArgs,
    PropOrderBookCleanup,
};

/// A second prop account for the same parent, freshly registered and with no
/// session of its own. `deploy_account` bakes `index` into the proxy, so a
/// different index is a different contract.
async fn sibling_account(
    fixture: &PropFixture,
    index: u64,
) -> (ContractId, PropAccountContract<Wallet>) {
    let parent = Identity::Address(fixture.user.address());
    let child = fixture
        .deployment
        .deploy_account(&fixture.user, parent, index)
        .await
        .unwrap();
    let child_id = child.contract_id();
    (
        child_id,
        PropAccountContract::new(child_id, fixture.user.clone()),
    )
}

/// Arms `session_id` on `account` for a day, exactly as the fixture arms its
/// own child.
async fn arm_session_key(
    account: &PropAccountContract<Wallet>,
    oracle_id: ContractId,
    session_id: Identity,
) {
    let expiry = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs()
        + 86_400;
    account
        .methods()
        .set_session(ParallelSessionArgs {
            nonce: U256::zero(),
            session_id,
            expiry: Time { unix: expiry },
            contract_ids: vec![],
        })
        .with_contract_ids(&[oracle_id])
        .call()
        .await
        .unwrap();
}

// ---------------------------------------------------------------------------
// The session key's blast radius.
// ---------------------------------------------------------------------------

/// The one property the whole session-key design rests on: a stolen key can
/// TRADE and it can spend, but it cannot name a payee. Every pool call it can
/// reach pays `session.parent` or the account itself, both of which the thief
/// does not control.
///
/// `require_target` deliberately WAIVES the tier allow-list when the target is
/// the pool, so the key genuinely reaches every pool method the ABI exposes -
/// including `withdraw`, which moves real money. What contains it is not the
/// allow-list but the pool's own routing: `withdraw` transfers to
/// `session.parent`, never to `msg_sender`.
#[tokio::test]
async fn a_stolen_session_key_can_spend_but_can_never_name_the_payee() {
    let mut fixture = PropFixture::new().await;

    // The fixture opens exactly at the tier floor, so top it up from outside:
    // the floor is a standing bound and no withdrawal may cross it.
    fixture.fund_collateral(500_000).await;

    let provider = fixture.user.try_provider().unwrap().clone();
    let parent = fixture.user.address();
    let thief = fixture.outsider.address();
    let parent_before = provider
        .get_asset_balance(&parent, &fixture.collateral_asset)
        .await
        .unwrap();
    let thief_before = provider
        .get_asset_balance(&thief, &fixture.collateral_asset)
        .await
        .unwrap();

    // The key reaches `withdraw` - no allow-list stands in its way - and the
    // call succeeds. The coins land on the PARENT.
    let withdraw = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.collateral_asset, 100_000u64)),
    );
    fixture.call_account(vec![withdraw], 2).await.unwrap();

    let parent_after = provider
        .get_asset_balance(&parent, &fixture.collateral_asset)
        .await
        .unwrap();
    let thief_after = provider
        .get_asset_balance(&thief, &fixture.collateral_asset)
        .await
        .unwrap();
    assert_eq!(
        parent_after - parent_before,
        100_000u128,
        "the withdrawal must reach the parent"
    );
    assert_eq!(
        thief_after, thief_before,
        "the session key names no payee: the thief is paid nothing"
    );

    // And the cash the key CAN move sits on the account, not in his pocket.
    let draw = fixture.draw_call(1_000_000);
    fixture.call_account(vec![draw], 1).await.unwrap();
    assert_eq!(
        fixture.account_balance(fixture.collateral_asset).await,
        1_000_000,
        "a draw funds the account contract, which only the parent can empty"
    );
}

/// The pool waiver is not a hole in the allow-list: everything OTHER than the
/// pool and the tier's own books is still refused, so a key cannot reach the
/// price feed, the registry or a book the tier never admitted.
#[tokio::test]
async fn a_session_key_reaches_the_pool_and_its_tier_books_and_nothing_else() {
    let mut fixture = PropFixture::new().await;

    // A tier book: allowed.
    let book_call = CallContractArg {
        contract_id: fixture.order_book.contract_id,
        function_selector: Bytes(fn_selector!(get_base_asset())),
        call_params: CallParams {
            coins: 0,
            asset_id: AssetId::default(),
            gas: 10_000_000,
        },
        call_data: None,
    };
    fixture.call_account(vec![book_call], 0).await.unwrap();

    // The price feed is a contract the pool itself reads on every marked path,
    // and it is still not a target this account may call.
    let feed_call = CallContractArg {
        contract_id: fixture.deployment.price_feed_id,
        function_selector: Bytes(fn_selector!(owner())),
        call_params: CallParams {
            coins: 0,
            asset_id: AssetId::default(),
            gas: 10_000_000,
        },
        call_data: None,
    };
    let error = fixture.call_account(vec![feed_call], 0).await.unwrap_err();
    assert!(
        error.to_string().contains("TargetNotAllowed"),
        "only the pool and the tier's books are reachable: {error:#}"
    );

    // A book that exists but was never admitted to the tier is refused too -
    // membership is the tier's, not the book's.
    let stranger_book = OrderBookDeploy::deploy(
        &fixture.deployer,
        AssetId::new([0x44; 32]),
        fixture.collateral_asset,
        &OrderBookDeployConfig::default(),
    )
    .await
    .unwrap();
    let stranger_call = CallContractArg {
        contract_id: stranger_book.contract_id,
        function_selector: Bytes(fn_selector!(get_base_asset())),
        call_params: CallParams {
            coins: 0,
            asset_id: AssetId::default(),
            gas: 10_000_000,
        },
        call_data: None,
    };
    let error = fixture
        .call_account(vec![stranger_call], 0)
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("TargetNotAllowed"),
        "an unlisted book is not a target: {error:#}"
    );
}

/// Closing the session takes the books away from the key. `is_call_allowed`
/// resolves through the account's PINNED tier, and settlement removes that
/// pin - so a key that outlives its session can no longer route an order
/// anywhere, and the pool methods it can still reach have nothing to act on.
///
/// Without this the account would keep a standing permission on every book
/// its last tier admitted, which is the difference between "a stale key is
/// useless" and "a stale key can trade the parent's own money".
#[tokio::test]
async fn closing_the_session_takes_the_books_away_from_the_key() {
    let mut fixture = PropFixture::new().await;

    async fn allowed(fixture: &PropFixture) -> bool {
        fixture
            .deployment
            .pool
            .methods()
            .is_call_allowed(fixture.child_id, fixture.order_book.contract_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    }
    assert!(allowed(&fixture).await);

    fixture.close_session().await;
    assert!(!allowed(&fixture).await, "the pin goes with the session");

    let book_call = CallContractArg {
        contract_id: fixture.order_book.contract_id,
        function_selector: Bytes(fn_selector!(get_base_asset())),
        call_params: CallParams {
            coins: 0,
            asset_id: AssetId::default(),
            gas: 10_000_000,
        },
        call_data: None,
    };
    let error = fixture.call_account(vec![book_call], 0).await.unwrap_err();
    assert!(
        error.to_string().contains("TargetNotAllowed"),
        "a key that outlived its session reaches no book: {error:#}"
    );

    // The pool is still reachable - the waiver is unconditional - but every
    // method behind it needs a session the account no longer has.
    let draw = fixture.draw_call(1);
    let error = fixture.call_account(vec![draw], 1).await.unwrap_err();
    assert!(
        error.to_string().contains("NoActiveSession"),
        "and nothing on the pool to act on: {error:#}"
    );
}

/// The pool waiver's real cost, stated as a test so it cannot regress
/// silently: a stolen key CAN burn the session's collateral on prolongation
/// fees. That is griefing, not theft - the coins go to the platform payout,
/// the ledger records every one of them, and the bound is the collateral.
#[tokio::test]
async fn a_stolen_session_key_can_grief_the_collateral_but_only_through_the_fee_ledger() {
    let mut fixture = PropFixture::new().await;

    let before = fixture.session().await;
    assert_eq!(before.fees_accrued, 0);

    let prolong = fixture.prolong_call(10);
    fixture.call_account(vec![prolong], 1).await.unwrap();

    let after = fixture.session().await;
    // 10 x the Day fee, and the line reprices off the collateral net of it.
    assert_eq!(after.fees_accrued, 60_000);
    assert_eq!(after.collateral, before.collateral);
    assert!(
        after.credit_line < before.credit_line,
        "burnt fees shrink the line one for one"
    );

    // And the burn is bounded: the fee may never reach the collateral.
    let prolong = fixture.prolong_call(1_000);
    let error = fixture.call_account(vec![prolong], 1).await.unwrap_err();
    assert!(
        error.to_string().contains("ProlongAboveCollateral"),
        "the grief stops at the collateral: {error:#}"
    );
}

// ---------------------------------------------------------------------------
// Signature and replay surface.
// ---------------------------------------------------------------------------

/// One nonce, one batch. The account commits the nonce before it runs a single
/// call, so resubmitting a captured transaction is refused by the bitmap rather
/// than by anything downstream.
#[tokio::test]
async fn a_captured_batch_cannot_be_replayed() {
    let mut fixture = PropFixture::new().await;

    let draw = fixture.draw_call(500_000);
    let (user_signature, cosigner_signature, calls) =
        fixture.signed_calls(vec![draw]).await;

    let submit = |fixture: &PropFixture| {
        fixture
            .account
            .methods()
            .call_contracts(
                user_signature.clone(),
                cosigner_signature.clone(),
                calls.clone(),
            )
            .with_contracts(&[
                &fixture.deployment.oracle,
                &fixture.deployment.pool,
                &fixture.deployment.price_feed,
                &fixture.deployment.registry,
                &fixture.order_book.order_book,
            ])
            .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
    };

    submit(&fixture).call().await.unwrap();
    assert_eq!(fixture.session().await.drawn_quote, 500_000);

    let error = submit(&fixture).call().await.unwrap_err();
    assert!(
        error.to_string().contains("AlreadyUsed"),
        "the second submission must be refused by the nonce bitmap: {error:#}"
    );
    assert_eq!(
        fixture.session().await.drawn_quote,
        500_000,
        "the replay moved nothing"
    );
}

/// Revoking the key stops the batch at the signature check, with the error the
/// client needs to tell "re-arm your key" from "you are not the owner".
#[tokio::test]
async fn a_revoked_or_expired_session_key_is_refused_as_a_signature_failure() {
    let mut fixture = PropFixture::new().await;

    // Armed: the batch runs.
    let draw = fixture.draw_call(100_000);
    fixture.call_account(vec![draw], 1).await.unwrap();

    fixture
        .account
        .methods()
        .revoke_session(ParallelRevokeArgs {
            nonce: U256::zero(),
        })
        .with_contract_ids(&[fixture.deployment.oracle_id])
        .call()
        .await
        .unwrap();
    assert!(
        fixture
            .account
            .methods()
            .get_current_session()
            .with_contract_ids(&[fixture.deployment.oracle_id])
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
            .is_none()
    );

    let draw = fixture.draw_call(100_000);
    let error = fixture.call_account(vec![draw], 1).await.unwrap_err();
    assert!(
        error.to_string().contains("InvalidUserSig"),
        "a revoked key is a signature failure, not a parenthood failure: {error:#}"
    );

    // A key armed with an expiry already behind the chain is refused at the
    // door rather than stored and quietly ignored.
    let latest = fixture
        .user
        .try_provider()
        .unwrap()
        .latest_block_time()
        .await
        .unwrap()
        .unwrap()
        .timestamp() as u64;
    let error = fixture
        .account
        .methods()
        .set_session(ParallelSessionArgs {
            nonce: U256::zero(),
            session_id: Identity::Address(fixture.user.address()),
            expiry: Time {
                unix: latest.saturating_sub(1),
            },
            contract_ids: vec![],
        })
        .with_contract_ids(&[fixture.deployment.oracle_id])
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("SessionInThePast"),
        "an already-dead key is refused at arming: {error:#}"
    );
}

/// Both signatures are load-bearing. A batch the user signed but the platform
/// did not is refused, so a stolen key alone buys nothing.
#[tokio::test]
async fn a_batch_without_the_platforms_cosignature_is_refused() {
    let mut fixture = PropFixture::new().await;

    let draw = fixture.draw_call(100_000);
    let (user_signature, _, calls) = fixture.signed_calls(vec![draw]).await;

    // The user cosigns his own batch. He is not the cosigner the oracle names.
    let chain_id = *fixture
        .user
        .provider()
        .consensus_parameters()
        .await
        .unwrap()
        .chain_id();
    let forged = fixture
        .user
        .signer()
        .sign(generate_trial_trade_approval_signing_payload(
            chain_id,
            fixture.child_id,
            calls.nonce,
            calls.call_contract_args.clone(),
        ))
        .await
        .unwrap();

    let error = fixture
        .account
        .methods()
        .call_contracts(
            user_signature,
            Signature::Secp256k1(Secp256k1 { bits: *forged }),
            calls,
        )
        .with_contracts(&[
            &fixture.deployment.oracle,
            &fixture.deployment.pool,
            &fixture.deployment.price_feed,
            &fixture.deployment.registry,
            &fixture.order_book.order_book,
        ])
        .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("InvalidCosigner"),
        "the platform's signature is not optional: {error:#}"
    );
}

/// The cosignature binds the ACCOUNT. A parent running two children under one
/// session key cannot have a batch cosigned for the first replayed against the
/// second - which is the whole reason `cosign_digest` hashes
/// `ContractId::this()`.
#[tokio::test]
async fn a_batch_cosigned_for_one_account_cannot_be_replayed_on_its_sibling() {
    let mut fixture = PropFixture::new().await;

    let (sibling_id, sibling) = sibling_account(&fixture, 1).await;
    arm_session_key(
        &sibling,
        fixture.deployment.oracle_id,
        Identity::Address(fixture.user.address()),
    )
    .await;

    // Signed for the fixture's child: the user leg does not name an account,
    // but the cosigner leg does.
    let draw = fixture.draw_call(100_000);
    let (user_signature, cosigner_signature, calls) =
        fixture.signed_calls(vec![draw]).await;

    let error = sibling
        .methods()
        .call_contracts(user_signature, cosigner_signature, calls)
        .with_contracts(&[
            &fixture.deployment.oracle,
            &fixture.deployment.pool,
            &fixture.deployment.price_feed,
            &fixture.deployment.registry,
            &fixture.order_book.order_book,
        ])
        .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("InvalidCosigner"),
        "the cosignature is bound to the account it was issued for: {error:#}"
    );
    assert!(
        fixture
            .deployment
            .pool
            .methods()
            .get_session(sibling_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
            .is_none(),
        "and the sibling never opened anything"
    );
}

// ---------------------------------------------------------------------------
// Parenthood.
// ---------------------------------------------------------------------------

/// Everything the OWNER route exposes is the parent's alone. A stranger
/// reaches none of it, whatever the account's session key says.
#[tokio::test]
async fn only_the_parent_arms_opens_closes_and_withdraws() {
    let fixture = PropFixture::new().await;

    let intruder = PropAccountContract::new(fixture.child_id, fixture.outsider.clone());
    let expiry = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs()
        + 86_400;

    let error = intruder
        .methods()
        .set_session(ParallelSessionArgs {
            nonce: U256::zero(),
            session_id: Identity::Address(fixture.outsider.address()),
            expiry: Time { unix: expiry },
            contract_ids: vec![],
        })
        .with_contract_ids(&[fixture.deployment.oracle_id])
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("NotParent"),
        "a stranger may not arm a key on someone else's account: {error:#}"
    );

    let error = intruder
        .methods()
        .revoke_session(ParallelRevokeArgs {
            nonce: U256::zero(),
        })
        .with_contract_ids(&[fixture.deployment.oracle_id])
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("NotParent"),
        "nor revoke one: {error:#}"
    );

    let error = intruder
        .methods()
        .close_session(Vec::<PropOrderBookCleanup>::new())
        .with_contracts(&[
            &fixture.deployment.pool,
            &fixture.deployment.oracle,
            &fixture.order_book.order_book,
            &fixture.deployment.price_feed,
        ])
        .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("NotParent"),
        "nor close the session out from under it: {error:#}"
    );

    let error = intruder
        .methods()
        .withdraw(fixture.collateral_asset, 1)
        .with_contracts(&[&fixture.deployment.pool, &fixture.deployment.oracle])
        .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("NotParent"),
        "nor drain it: {error:#}"
    );

    let error = intruder
        .methods()
        .start_session(TIER_ID, 1, ProlongPeriod::SixHours)
        .call_params(CallParameters::new(1, fixture.collateral_asset, u64::MAX))
        .unwrap()
        .with_contract_ids(&[
            fixture.deployment.oracle_id,
            fixture.deployment.pool_id,
            fixture.deployment.registry_id,
        ])
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("NotParent"),
        "nor open one on it: {error:#}"
    );
}

/// The three pool callbacks move assets and cancel orders with no signature of
/// any kind, so the pool is the only caller they accept. `pool_release` in
/// particular takes an arbitrary payee - it would be a drain of every account
/// on the system if the guard were missing.
#[tokio::test]
async fn only_the_pool_can_drive_cleanup_release_and_sweep() {
    let mut fixture = PropFixture::new().await;

    // Put something on the account worth stealing.
    let draw = fixture.draw_call(1_000_000);
    fixture.call_account(vec![draw], 1).await.unwrap();
    assert_eq!(
        fixture.account_balance(fixture.collateral_asset).await,
        1_000_000
    );

    for caller in [fixture.outsider.clone(), fixture.user.clone()] {
        let account = PropAccountContract::new(fixture.child_id, caller.clone());

        let error = account
            .methods()
            .pool_release(
                fixture.collateral_asset,
                1_000_000,
                Identity::Address(fixture.outsider.address()),
            )
            .with_contracts(&[&fixture.deployment.pool, &fixture.deployment.oracle])
            .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
            .call()
            .await
            .unwrap_err();
        assert!(
            error.to_string().contains("NotPool"),
            "release names its own payee, so only the pool may call it: {error:#}"
        );

        let error = account
            .methods()
            .pool_sweep(vec![fixture.collateral_asset])
            .with_contracts(&[&fixture.deployment.pool, &fixture.deployment.oracle])
            .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
            .call()
            .await
            .unwrap_err();
        assert!(
            error.to_string().contains("NotPool"),
            "nor may anyone else push the account's balance into settlement: {error:#}"
        );

        let error = account
            .methods()
            .pool_cleanup(vec![PropOrderBookCleanup {
                order_book: fixture.order_book.contract_id,
                order_ids: vec![],
            }])
            .with_contracts(&[
                &fixture.deployment.pool,
                &fixture.deployment.oracle,
                &fixture.order_book.order_book,
            ])
            .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
            .call()
            .await
            .unwrap_err();
        assert!(
            error.to_string().contains("NotPool"),
            "nor cancel its orders: {error:#}"
        );
    }

    assert_eq!(
        fixture.account_balance(fixture.collateral_asset).await,
        1_000_000,
        "not one coin moved"
    );
}

// ---------------------------------------------------------------------------
// Opening and emptying an account.
// ---------------------------------------------------------------------------

/// `start_session` opens on EXACTLY the amount named. Anything else the
/// account happens to be holding - a stray airdrop, a leftover from a previous
/// session, an overpayment - goes home to the parent first, which is what
/// lets the pool insist the account is empty at open.
#[tokio::test]
async fn opening_a_session_returns_every_stray_balance_to_the_parent() {
    let fixture = PropFixture::new().await;
    let (sibling_id, sibling) = sibling_account(&fixture, 2).await;

    // A stray of each tier asset, plus more collateral than the session wants.
    let stray_base = 7_000_000_000u64;
    let overpay = 250_000u64;
    fixture
        .deployer
        .force_transfer_to_contract(
            sibling_id,
            stray_base,
            fixture.base_asset,
            TxPolicies::default(),
        )
        .await
        .unwrap();

    let provider = fixture.user.try_provider().unwrap();
    let parent = fixture.user.address();
    let base_before = provider
        .get_asset_balance(&parent, &fixture.base_asset)
        .await
        .unwrap();

    let error = sibling
        .methods()
        .start_session(TIER_ID, COLLATERAL, ProlongPeriod::SixHours)
        .call_params(CallParameters::new(
            COLLATERAL + overpay,
            fixture.collateral_asset,
            u64::MAX,
        ))
        .unwrap()
        .with_contracts(&[
            &fixture.deployment.oracle,
            &fixture.deployment.pool,
            &fixture.deployment.registry,
        ])
        .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("PaymentAmountMismatch"),
        "the coins sent must equal the amount signed for: {error:#}"
    );

    // The overpayment is refused outright rather than silently absorbed: the
    // amount the parent signs for is the amount the session opens on.
    let session = fixture
        .deployment
        .pool
        .methods()
        .get_session(sibling_id)
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value;
    assert!(
        session.is_none(),
        "a payment that disagrees with the named amount opens nothing"
    );

    // Paid correctly, the stray base asset is swept home and the session opens
    // on exactly the named collateral.
    sibling
        .methods()
        .start_session(TIER_ID, COLLATERAL, ProlongPeriod::SixHours)
        .call_params(CallParameters::new(
            COLLATERAL,
            fixture.collateral_asset,
            u64::MAX,
        ))
        .unwrap()
        .with_contract_ids(&[
            fixture.deployment.oracle_id,
            fixture.deployment.pool_id,
            fixture.deployment.registry_id,
        ])
        .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
        .call()
        .await
        .unwrap();

    let base_after = provider
        .get_asset_balance(&parent, &fixture.base_asset)
        .await
        .unwrap();
    assert_eq!(
        base_after - base_before,
        stray_base as u128,
        "the stray base asset went home to the parent"
    );
    let session = fixture
        .deployment
        .pool
        .methods()
        .get_session(sibling_id)
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value
        .unwrap();
    assert_eq!(session.collateral, COLLATERAL);
    assert_eq!(session.session_id, 1);
}

/// The other three ways an opening can be wrong, each refused by its own
/// error: no money, the wrong money, and a seat already taken.
#[tokio::test]
async fn opening_refuses_a_zero_entry_the_wrong_asset_and_a_second_seat() {
    let fixture = PropFixture::new().await;
    let (_, sibling) = sibling_account(&fixture, 3).await;

    // The account no longer gates zero - a fully forgiven PREPAID entry
    // opens on zero coins - so a zero LEGACY entry travels to the pool
    // and dies on its own funding rule instead.
    let error = sibling
        .methods()
        .start_session(TIER_ID, 0, ProlongPeriod::SixHours)
        .call_params(CallParameters::new(0, fixture.collateral_asset, u64::MAX))
        .unwrap()
        .with_contracts(&[
            &fixture.deployment.oracle,
            &fixture.deployment.pool,
            &fixture.deployment.registry,
        ])
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("CollateralTooSmall"),
        "a free seat is not on offer on a legacy tier: {error:#}"
    );

    let error = sibling
        .methods()
        .start_session(TIER_ID, COLLATERAL, ProlongPeriod::SixHours)
        .call_params(CallParameters::new(
            COLLATERAL,
            fixture.base_asset,
            u64::MAX,
        ))
        .unwrap()
        .with_contract_ids(&[
            fixture.deployment.oracle_id,
            fixture.deployment.pool_id,
            fixture.deployment.registry_id,
        ])
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("WrongAsset"),
        "collateral is the collateral asset: {error:#}"
    );

    // The fixture's own child already holds a session.
    let error = fixture
        .account
        .methods()
        .start_session(TIER_ID, COLLATERAL, ProlongPeriod::SixHours)
        .call_params(CallParameters::new(
            COLLATERAL,
            fixture.collateral_asset,
            u64::MAX,
        ))
        .unwrap()
        .with_contract_ids(&[
            fixture.deployment.oracle_id,
            fixture.deployment.pool_id,
            fixture.deployment.registry_id,
        ])
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("SessionActive"),
        "one seat per account: {error:#}"
    );
}

/// `withdraw` on the ACCOUNT is the post-session escape hatch, not a second
/// way out of a live one: while a session exists the pool's own `withdraw`
/// (with its floor, its share and its debt gates) is the only route, and the
/// account refuses to bypass it.
#[tokio::test]
async fn the_accounts_own_withdrawal_waits_until_the_session_is_gone() {
    let mut fixture = PropFixture::new().await;

    let draw = fixture.draw_call(1_000_000);
    fixture.call_account(vec![draw], 1).await.unwrap();

    let error = fixture
        .account
        .methods()
        .withdraw(fixture.collateral_asset, 1_000_000)
        .with_contracts(&[&fixture.deployment.pool, &fixture.deployment.oracle])
        .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("SessionActive"),
        "the pool's rules cannot be walked around while a session lives: {error:#}"
    );

    // Clear the draw, close cleanly, and the hatch opens.
    let repay = fixture.pool_call(
        fn_selector!(return_quote()),
        1_000_000,
        fixture.collateral_asset,
        None,
    );
    fixture.call_account(vec![repay], 0).await.unwrap();
    fixture.close_session().await;

    // The close paid the parent, so gift the account something to withdraw.
    fixture
        .deployer
        .force_transfer_to_contract(
            fixture.child_id,
            123_456,
            fixture.collateral_asset,
            TxPolicies::default(),
        )
        .await
        .unwrap();

    let response = fixture
        .account
        .methods()
        .withdraw(fixture.collateral_asset, 123_456)
        .with_contracts(&[&fixture.deployment.pool, &fixture.deployment.oracle])
        .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
        .call()
        .await
        .unwrap();
    let events = response
        .decode_logs_with_type::<MarginTradeAccountWithdrawn>()
        .unwrap();
    assert_eq!(events.len(), 1);
    assert_eq!(events[0].account, fixture.child_id);
    assert_eq!(events[0].parent, Identity::Address(fixture.user.address()));
    assert_eq!(events[0].amount, 123_456);
    assert!(events[0].timestamp.unix != 0);

    let error = fixture
        .account
        .methods()
        .withdraw(fixture.collateral_asset, 0)
        .with_contracts(&[&fixture.deployment.pool, &fixture.deployment.oracle])
        .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("AmountIsZero"),
        "a zero withdrawal is a no-op worth refusing: {error:#}"
    );
}