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
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
//! Exits with the order book in the picture, and the account's second life.
//!
//! Every existing exit test hands the pool an EMPTY cleanup list, so the whole
//! cancel-then-drain half of `absorb` was untested. That half is where the
//! liveness risk lives: a lock the pool cannot see is a session nobody can
//! close, and a lock the pool forgets to count is a seizure at the wrong price.

use super::*;
use crate::{
    order_book_deploy::Side,
    prop::PropOrderBookCleanup,
};

/// The account's resting order on the fixture's book at `price`, as the pool's
/// cleanup list wants it.
async fn resting_cleanup(
    fixture: &PropFixture,
    side: Side,
    price: u64,
) -> PropOrderBookCleanup {
    let orders = fixture
        .order_book
        .order_book
        .methods()
        .get_orders_at_price(side, price)
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value;
    let order_ids = orders
        .into_iter()
        .filter(|order| order.trader_id == Identity::ContractId(fixture.child_id))
        .map(|order| order.order_id)
        .collect::<Vec<_>>();
    assert!(!order_ids.is_empty(), "the account has no resting order");
    PropOrderBookCleanup {
        order_book: fixture.order_book.contract_id,
        order_ids,
    }
}

#[tokio::test]
async fn permissioned_closure_drains_every_order_and_settles_all_session_legs() {
    assert_permissioned_closure_drains_every_leg(false).await;
}

#[tokio::test]
async fn signed_closure_drains_every_order_and_settles_all_session_legs() {
    assert_permissioned_closure_drains_every_leg(true).await;
}

async fn permissioned_close(
    fixture: &PropFixture,
    authorization: &Option<(u64, Signature)>,
    cleanups: Vec<PropOrderBookCleanup>,
) -> Result<CallResponse<()>> {
    match authorization {
        Some((session, signature)) => {
            fixture
                .force_close_session_signed(
                    &fixture.user,
                    *session,
                    cleanups,
                    signature.clone(),
                )
                .await
        }
        None => {
            fixture
                .force_close_session(&fixture.deployer, cleanups)
                .await
        }
    }
}

async fn assert_permissioned_closure_drains_every_leg(signed: bool) {
    let mut fixture = PropFixture::new().await;
    let authorization = if signed {
        fixture
            .deployment
            .pool
            .methods()
            .set_expiry_cosigner(fixture.deployer.address())
            .call()
            .await
            .unwrap();
        let session = fixture.session().await.session_id;
        Some((
            session,
            fixture
                .force_close_cosignature(session, &fixture.deployer)
                .await,
        ))
    } else {
        None
    };
    let borrowed = 100_000_000;
    let gift = 100_000_000;
    let drawn = 1_000_000;
    let liquidator = Identity::Address(fixture.outsider.address());
    fixture
        .deployment
        .pool
        .methods()
        .set_liquidator(liquidator)
        .call()
        .await
        .unwrap();
    fixture
        .deployer
        .force_transfer_to_contract(
            fixture.child_id,
            gift,
            fixture.base_asset,
            TxPolicies::default(),
        )
        .await
        .unwrap();
    let borrow = fixture.pool_call(
        fn_selector!(borrow(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.base_asset, borrowed)),
    );
    let draw = fixture.draw_call(drawn);
    let buy =
        fixture.book_call(1_000_000, 1_000_000_000, fixture.collateral_asset, drawn);
    let sell = fixture.book_call(
        3_000_000,
        borrowed + gift,
        fixture.base_asset,
        borrowed + gift,
    );
    fixture
        .call_account(vec![borrow, draw, buy, sell], 2)
        .await
        .unwrap();
    let buy_cleanup = resting_cleanup(&fixture, Side::Buy, 1_000_000).await;
    let sell_cleanup = resting_cleanup(&fixture, Side::Sell, 3_000_000).await;
    assert_eq!(fixture.account_balance(fixture.collateral_asset).await, 0);
    assert_eq!(fixture.account_balance(fixture.base_asset).await, 0);

    // Cancelling only one leg must roll back the cancellation and its drain.
    let session_before = fixture.session().await;
    let pool_base_before = fixture.pool_balance(fixture.base_asset).await;
    let pool_cash_before = fixture.pool_balance(fixture.collateral_asset).await;
    let error = permissioned_close(&fixture, &authorization, vec![buy_cleanup.clone()])
        .await
        .unwrap_err();
    assert!(error.to_string().contains("BookNotDrained"), "{error:#}");
    assert_eq!(
        resting_cleanup(&fixture, Side::Buy, 1_000_000)
            .await
            .order_ids,
        buy_cleanup.order_ids
    );
    assert_eq!(fixture.account_balance(fixture.collateral_asset).await, 0);
    assert_eq!(fixture.session().await.drawn_quote, drawn);
    assert_eq!(fixture.debt(fixture.base_asset).await, borrowed);
    assert_eq!(fixture.session().await, session_before);
    assert_eq!(
        fixture.pool_balance(fixture.base_asset).await,
        pool_base_before
    );
    assert_eq!(
        fixture.pool_balance(fixture.collateral_asset).await,
        pool_cash_before
    );
    assert_eq!(
        resting_cleanup(&fixture, Side::Sell, 3_000_000)
            .await
            .order_ids,
        sell_cleanup.order_ids
    );

    let liquidator_before = fixture
        .outsider
        .get_asset_balance(&fixture.base_asset)
        .await
        .unwrap();
    let pool_cash_before = fixture.pool_balance(fixture.collateral_asset).await;
    let mut recipient_balances = Vec::new();
    for wallet in [&fixture.user, &fixture.deployer] {
        recipient_balances.push((
            wallet.get_asset_balance(&fixture.base_asset).await.unwrap(),
            wallet
                .get_asset_balance(&fixture.collateral_asset)
                .await
                .unwrap(),
        ));
    }
    // The same authorization accepts corrected cleanup inputs after the revert.
    let response =
        permissioned_close(&fixture, &authorization, vec![buy_cleanup, sell_cleanup])
            .await
            .unwrap();
    let closed = fixture.closed_event(&response);
    assert_eq!(closed.reason, SettlementReason::PermissionedClosure);
    assert_eq!(closed.v, LINE + 200_000);
    assert_eq!(closed.v_liq, LINE + 198_000);
    assert_eq!(closed.profit_abs, 198_000);
    assert!(!closed.profit_is_negative);
    assert_eq!(closed.platform_total, 19_800);
    assert_eq!(closed.user_net, COLLATERAL + 198_000 - 19_800);
    assert_eq!(closed.bad_debt, 0);
    assert!(closed.cancelled_debt.is_empty());
    let seized = response.decode_logs_with_type::<SessionSeized>().unwrap();
    assert_eq!(seized.len(), 1);
    assert_eq!(seized[0].reason, SettlementReason::PermissionedClosure);
    assert_eq!(seized[0].liquidator, liquidator);
    assert_eq!(seized[0].debt, vec![(fixture.base_asset, borrowed)]);
    assert_eq!(seized[0].transferred, vec![(fixture.base_asset, borrowed)]);
    assert_eq!(
        fixture
            .outsider
            .get_asset_balance(&fixture.base_asset)
            .await
            .unwrap()
            - liquidator_before,
        borrowed as u128
    );
    for ((wallet, payouts), (base_before, cash_before)) in [
        (&fixture.user, &closed.payout_parent),
        (&fixture.deployer, &closed.payout_platform),
    ]
    .into_iter()
    .zip(recipient_balances)
    {
        for (asset, before) in [
            (fixture.base_asset, base_before),
            (fixture.collateral_asset, cash_before),
        ] {
            let payout: u64 = payouts
                .iter()
                .filter(|(id, _)| *id == asset)
                .map(|(_, quantity)| *quantity)
                .sum();
            assert!(payout > 0);
            assert_eq!(
                wallet.get_asset_balance(&asset).await.unwrap() - before,
                payout as u128
            );
        }
    }
    assert_eq!(
        fixture.pool_balance(fixture.collateral_asset).await,
        pool_cash_before + drawn - COLLATERAL
    );
    assert_eq!(fixture.account_balance(fixture.base_asset).await, 0);
    assert_eq!(fixture.account_balance(fixture.collateral_asset).await, 0);
    assert_eq!(
        fixture
            .order_book
            .order_book
            .methods()
            .get_total_balance_of(Identity::ContractId(fixture.child_id))
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        (0, 0)
    );
    assert_eq!(fixture.debt(fixture.base_asset).await, 0);
    assert!(fixture.session_opt().await.is_none());
}

#[tokio::test]
async fn permissioned_closure_and_liquidation_settle_the_same_uncovered_short() {
    for permissioned in [false, true] {
        let mut fixture = PropFixture::new().await;
        let quantity = 1_000_000_000;
        let sale = 2_000_000;
        let drawn = 3_000_000;
        fixture
            .deployment
            .pool
            .methods()
            .set_liquidator(Identity::Address(fixture.outsider.address()))
            .call()
            .await
            .unwrap();
        fixture
            .rest_order(sale, quantity, fixture.collateral_asset, sale)
            .await;
        let borrow = fixture.pool_call(
            fn_selector!(borrow(AssetId, u64)),
            0,
            AssetId::default(),
            Some(call_data!(fixture.base_asset, quantity)),
        );
        let draw = fixture.draw_call(drawn);
        let sell = fixture.book_call(sale, quantity, fixture.base_asset, quantity);
        fixture
            .call_account(vec![borrow, draw, sell, fixture.settle_book_call()], 2)
            .await
            .unwrap();
        fixture.publish_base_price(20_000_000_000_000_000_000).await;
        assert!(fixture.is_liquidatable().await);
        let liquidator_before = fixture
            .outsider
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap();
        let pool_cash_before = fixture.pool_balance(fixture.collateral_asset).await;
        let response = if permissioned {
            fixture
                .force_close_session(&fixture.deployer, vec![])
                .await
                .unwrap()
        } else {
            fixture.liquidate().await
        };
        let reason = if permissioned {
            SettlementReason::PermissionedClosure
        } else {
            SettlementReason::Liquidation
        };
        let closed = fixture.closed_event(&response);
        assert_eq!(closed.reason, reason);
        assert_eq!(closed.cancelled_debt, vec![(fixture.base_asset, quantity)]);
        assert_eq!(closed.profit_abs, 18_202_021);
        assert!(closed.profit_is_negative);
        assert_eq!(closed.bad_debt, 16_202_021);
        assert_eq!(closed.user_net, 0);
        assert_eq!(closed.platform_total, 0);
        assert_eq!(fixture.bad_debt().await, closed.bad_debt);
        let seized = response.decode_logs_with_type::<SessionSeized>().unwrap();
        assert_eq!(seized.len(), 1);
        assert_eq!(seized[0].reason, reason);
        assert_eq!(seized[0].debt, vec![(fixture.base_asset, quantity)]);
        assert_eq!(
            seized[0].holdings,
            vec![(fixture.collateral_asset, drawn + sale)]
        );
        assert_eq!(
            seized[0].transferred,
            vec![(fixture.collateral_asset, COLLATERAL + sale)]
        );
        assert_eq!(
            fixture
                .outsider
                .get_asset_balance(&fixture.collateral_asset)
                .await
                .unwrap()
                - liquidator_before,
            (COLLATERAL + sale) as u128
        );
        assert_eq!(
            fixture.pool_balance(fixture.collateral_asset).await,
            pool_cash_before + drawn - COLLATERAL
        );
        assert_eq!(fixture.account_balance(fixture.collateral_asset).await, 0);
        assert_eq!(fixture.debt(fixture.base_asset).await, 0);
        assert!(fixture.session_opt().await.is_none());
    }
}

// ---------------------------------------------------------------------------
// A resting order at the door.
// ---------------------------------------------------------------------------

/// A session cannot leave while any of its value is still locked in a book.
/// The pool has no way to price an open order, so it insists the books are
/// EMPTY - and gives the caller the one tool that empties them, the cleanup
/// list it drives through the account before it looks.
#[tokio::test]
async fn a_close_is_refused_while_an_order_rests_and_the_cleanup_list_frees_it() {
    let mut fixture = PropFixture::new().await;

    // Draw, then park the whole draw in an unfilled buy well below the market.
    let draw = fixture.draw_call(1_000_000);
    let rest = fixture.book_call(
        1_000_000,
        1_000_000_000,
        fixture.collateral_asset,
        1_000_000,
    );
    fixture.call_account(vec![draw, rest], 1).await.unwrap();
    assert_eq!(fixture.account_balance(fixture.collateral_asset).await, 0);

    // Net the draw away so the close's own gates are satisfied and the book is
    // the only thing left standing between the session and the door.
    let net = fixture.repay_from_collateral_call(1_000_000);
    fixture.call_account(vec![net], 0).await.unwrap();
    assert_eq!(fixture.session().await.drawn_quote, 0);

    let error = fixture
        .account
        .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("BookNotDrained"),
        "value locked in a book cannot be settled at any price: {error:#}"
    );

    // Handed the order, the pool cancels it through the account, settles the
    // book, and only then values what came home.
    let cleanup = resting_cleanup(&fixture, Side::Buy, 1_000_000).await;
    let parent_before = fixture
        .user
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    let response = fixture
        .account
        .methods()
        .close_session(vec![cleanup])
        .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();
    let closed = fixture.closed_event(&response);
    assert_eq!(closed.reason, SettlementReason::UserClose);
    assert_eq!(closed.bad_debt, 0);
    assert_eq!(
        closed.platform_total, 0,
        "the netting is principal coming home, not profit"
    );
    assert_eq!(closed.user_net, COLLATERAL);
    assert_eq!(
        fixture
            .user
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap()
            - parent_before,
        COLLATERAL as u128,
        "the whole entry came back to the parent"
    );
    assert_eq!(
        fixture
            .order_book
            .order_book
            .methods()
            .get_total_balance_of(Identity::ContractId(fixture.child_id))
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        (0, 0)
    );
}

/// The same rule from the keeper's side, and it is the one that matters most:
/// a session whose whole value is resting in an order LOOKS underwater to the
/// pool, because the valuation walk counts what the account holds and a book
/// lock is not held by the account.
///
/// The drain check is what makes that safe. The keeper must cancel first, and
/// once the cash is home the session values correctly - so the order cannot be
/// used to manufacture a seizure, and the pool cannot seize around it either.
#[tokio::test]
async fn a_keeper_must_cancel_before_it_can_judge_and_the_cancel_answers_the_judgement() {
    let mut fixture = PropFixture::new().await;

    // 1_800_000 drawn and entirely locked in an unfilled buy. Without the cash
    // on the account the legs read 8_200_000 against a threshold of 8_250_000.
    let draw = fixture.draw_call(1_800_000);
    let rest = fixture.book_call(
        1_000_000,
        1_800_000_000,
        fixture.collateral_asset,
        1_800_000,
    );
    fixture.call_account(vec![draw, rest], 1).await.unwrap();
    assert_eq!(fixture.account_balance(fixture.collateral_asset).await, 0);

    let keeper = fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone());

    // Empty-handed, the keeper is stopped by the drain check before the
    // liquidation gate is ever evaluated.
    let error = keeper
        .methods()
        .liquidate(fixture.child_id, vec![])
        .with_contracts(&[
            &fixture.account,
            &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("BookNotDrained"),
        "the gate is never read against a half-visible portfolio: {error:#}"
    );

    // Handed the order, the cancel runs first - and the cash it returns is
    // exactly what lifts the session back over the line.
    let cleanup = resting_cleanup(&fixture, Side::Buy, 1_000_000).await;
    let error = keeper
        .methods()
        .liquidate(fixture.child_id, vec![cleanup])
        .with_contracts(&[
            &fixture.account,
            &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("NotLiquidatable"),
        "a session is judged on the cash the cancel brought home: {error:#}"
    );

    // The cancel happened even though the liquidation reverted? No - the whole
    // call rolled back, order and all, so the session is exactly as it was.
    assert_eq!(fixture.account_balance(fixture.collateral_asset).await, 0);
    assert_eq!(fixture.session().await.drawn_quote, 1_800_000);
    assert_ne!(
        fixture
            .order_book
            .order_book
            .methods()
            .get_total_balance_of(Identity::ContractId(fixture.child_id))
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        (0, 0),
        "a refused seizure leaves the order resting"
    );
}

/// Two markets, two locks, one exit. The drain check walks EVERY book in the
/// tier, so a cleanup list that frees one and forgets the other is refused -
/// which is what stops a session leaving value behind on a market nobody
/// remembered.
#[tokio::test]
async fn a_two_market_session_must_free_both_books_before_it_closes() {
    let mut fixture = PropFixture::new().await;

    // A second market in the same tier, admitted mid-session.
    let second_base = AssetId::new([0x91; 32]);
    let second = OrderBookDeploy::deploy(
        &fixture.deployer,
        second_base,
        fixture.collateral_asset,
        &OrderBookDeployConfig::default(),
    )
    .await
    .unwrap();
    fixture
        .deployment
        .price_feed
        .methods()
        .set_asset_decimals(second_base, 9)
        .call()
        .await
        .unwrap();
    fixture
        .deployment
        .price_feed
        .methods()
        .publish_prices(vec![PriceInput {
            asset: second_base,
            bid: 2_000_000_000_000_000_000u64.into(),
            ask: 2_000_000_000_000_000_000u64.into(),
            timestamp: fixture.next_publish_time(),
        }])
        .call()
        .await
        .unwrap();
    fixture
        .deployment
        .pool
        .methods()
        .add_books(TIER_ID, vec![second.contract_id])
        .with_contract_ids(&[second.contract_id, fixture.deployment.price_feed_id])
        .call()
        .await
        .unwrap();

    // Draw once, rest a buy on each market.
    let draw = fixture.draw_call(2_000_000);
    let rest_first = fixture.book_call(
        1_000_000,
        1_000_000_000,
        fixture.collateral_asset,
        1_000_000,
    );
    let rest_second = CallContractArg {
        contract_id: second.contract_id,
        function_selector: Bytes(fn_selector!(create_order(OrderArgs))),
        call_params: CallParams {
            coins: 1_000_000,
            asset_id: fixture.collateral_asset,
            gas: 10_000_000,
        },
        call_data: Some(Bytes(call_data!(OrderArgs {
            price: 1_000_000,
            quantity: 1_000_000_000,
            order_type: OrderType::Spot,
        }))),
    };
    let (user_signature, cosigner_signature, calls) = fixture
        .signed_calls(vec![draw, rest_first, rest_second])
        .await;
    fixture
        .account
        .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,
            &second.order_book,
        ])
        .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
        .call()
        .await
        .unwrap();

    let net = fixture.repay_from_collateral_call(2_000_000);
    fixture.call_account(vec![net], 0).await.unwrap();

    let first_cleanup = resting_cleanup(&fixture, Side::Buy, 1_000_000).await;
    let second_orders = second
        .order_book
        .methods()
        .get_orders_at_price(Side::Buy, 1_000_000)
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value;
    let second_cleanup = PropOrderBookCleanup {
        order_book: second.contract_id,
        order_ids: second_orders
            .into_iter()
            .filter(|order| order.trader_id == Identity::ContractId(fixture.child_id))
            .map(|order| order.order_id)
            .collect(),
    };
    assert_eq!(second_cleanup.order_ids.len(), 1);

    // Freeing only the first market is not enough.
    let error = fixture
        .account
        .methods()
        .close_session(vec![first_cleanup.clone()])
        .with_contracts(&[
            &fixture.deployment.pool,
            &fixture.deployment.oracle,
            &fixture.order_book.order_book,
            &second.order_book,
            &fixture.deployment.price_feed,
        ])
        .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("BookNotDrained"),
        "the drain check walks every book the tier admitted: {error:#}"
    );

    // Both, and the session leaves with everything it came in with.
    let parent_before = fixture
        .user
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    let response = fixture
        .account
        .methods()
        .close_session(vec![first_cleanup, second_cleanup])
        .with_contracts(&[
            &fixture.deployment.pool,
            &fixture.deployment.oracle,
            &fixture.order_book.order_book,
            &second.order_book,
            &fixture.deployment.price_feed,
        ])
        .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
        .call()
        .await
        .unwrap();
    let closed = fixture.closed_event(&response);
    assert_eq!(closed.reason, SettlementReason::UserClose);
    assert_eq!(closed.bad_debt, 0);
    assert_eq!(closed.user_net, COLLATERAL);
    assert_eq!(
        fixture
            .user
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap()
            - parent_before,
        COLLATERAL as u128
    );
}

// ---------------------------------------------------------------------------
// The account's second life.
// ---------------------------------------------------------------------------

/// Session IDs are never reused, and every accounting key is scoped by one.
/// A trader who closes and reopens gets a clean ledger rather than the
/// remains of the last one - which is what makes an account a durable
/// identity instead of a one-shot vehicle.
#[tokio::test]
async fn a_second_session_on_the_same_account_starts_from_a_clean_ledger() {
    let mut fixture = PropFixture::new().await;

    // A first life with everything the ledger can carry: a draw, an in-kind
    // debt, an accrued fee and a settlement receipt.
    let draw = fixture.draw_call(1_000_000);
    let borrow = fixture.pool_call(
        fn_selector!(borrow(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.base_asset, 500_000_000u64)),
    );
    fixture.call_account(vec![draw, borrow], 2).await.unwrap();
    fixture
        .call_account(vec![fixture.prolong_call(1)], 1)
        .await
        .unwrap();

    let first = fixture.session().await;
    assert_eq!(first.session_id, 1);
    assert_eq!(first.fees_accrued, 6_000);

    let repay =
        fixture.pool_call(fn_selector!(repay()), 500_000_000, fixture.base_asset, None);
    let give_back = fixture.pool_call(
        fn_selector!(return_quote()),
        1_000_000,
        fixture.collateral_asset,
        None,
    );
    fixture
        .call_account(vec![repay, give_back], 0)
        .await
        .unwrap();
    fixture.close_session().await;

    // The parent takes the settlement home and posts it again.
    let second_entry = COLLATERAL;
    let response = fixture
        .account
        .methods()
        .start_session(TIER_ID, second_entry, ProlongPeriod::SixHours)
        .call_params(CallParameters::new(
            second_entry,
            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 opened = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionOpened>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(opened.len(), 1);
    assert_eq!(
        opened[0].session_id, 2,
        "IDs are monotonic, so the old keys can never be addressed again"
    );

    let second = fixture.session().await;
    assert_eq!(second.session_id, 2);
    assert_eq!(second.collateral, second_entry);
    assert_eq!(second.drawn_quote, 0, "the old draw did not follow it");
    assert_eq!(second.fees_accrued, 0, "nor the old fee");
    assert_eq!(second.capitalised, 0);
    assert_eq!(second.decapitalised, 0);
    assert_eq!(second.credit_line, 10_000_000);
    assert_eq!(fixture.debt(fixture.base_asset).await, 0);
    assert!(
        !fixture
            .deployment
            .pool
            .methods()
            .has_debts(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    );

    // And the second life closes as cleanly as the first.
    fixture.close_session().await;
}

/// The sweep is scoped to the TIER's assets, so anything else the account is
/// holding is untouched by a close - it is not swept, not valued, not shared,
/// and it is still there for the parent afterwards. An airdrop is the user's,
/// not the pool's.
#[tokio::test]
async fn an_off_tier_holding_is_untouched_by_the_close_and_leaves_with_the_parent() {
    let fixture = PropFixture::new().await;

    let gift = AssetId::default();
    fixture
        .deployer
        .force_transfer_to_contract(fixture.child_id, 4_242, gift, TxPolicies::default())
        .await
        .unwrap();
    let held = fixture.account_balance(gift).await;
    assert!(held != 0);

    fixture.close_session().await;
    assert_eq!(
        fixture.account_balance(gift).await,
        held,
        "an asset outside the tier is not part of the settlement basket"
    );

    // With the session gone the parent can take it.
    let parent_before = fixture.user.get_asset_balance(&gift).await.unwrap();
    fixture
        .account
        .methods()
        .withdraw(gift, held)
        .with_contracts(&[&fixture.deployment.pool, &fixture.deployment.oracle])
        .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
        .call()
        .await
        .unwrap();
    assert!(
        fixture.user.get_asset_balance(&gift).await.unwrap() > parent_before,
        "and it leaves with the parent"
    );
    assert_eq!(fixture.account_balance(gift).await, 0);
}

// ---------------------------------------------------------------------------
// Who may open one at all.
// ---------------------------------------------------------------------------

/// Registration is the ONLY thing that brings a prop account to life. The
/// proxy bakes its parent into its bytecode but keeps it out of storage until
/// the registry writes it, and the registry writes it only for the parent
/// itself, only once, and only over a proxy pointing at the oracle's current
/// implementation.
///
/// So an unregistered proxy - byte-for-byte identical to a real one - is
/// INERT: it has no parent, so nothing on it can be authorised. The pool's own
/// `NotPropAccount` sits behind that as a second lock.
#[tokio::test]
async fn an_unregistered_account_is_inert_until_its_parent_registers_it() {
    let fixture = PropFixture::new().await;

    let parent = Identity::Address(fixture.user.address());
    let configurables = PropAccountProxyContractConfigurables::default()
        .with_ORACLE_CONTRACT_ID(fixture.deployment.oracle_id)
        .unwrap()
        .with_PARENT(parent)
        .unwrap()
        .with_INDEX(99)
        .unwrap();
    let contract = regular_contract(
        PROP_ACCOUNT_PROXY_BYTECODE,
        PROP_ACCOUNT_PROXY_STORAGE,
        fixture.deployment.account_salt,
    )
    .unwrap()
    .with_configurables(configurables);
    let (unregistered_id, _) = deploy_regular(&fixture.user, contract).await.unwrap();

    let registry = &fixture.deployment.registry;
    assert!(
        !registry
            .methods()
            .prop_is_valid(unregistered_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    );

    // Inert: the parent is baked into the bytecode but not into storage, so
    // even the owner route cannot authorise anything.
    let unregistered = PropAccountContract::new(unregistered_id, fixture.user.clone());
    let error = unregistered
        .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_err();
    assert!(
        error.to_string().contains("InvalidParent"),
        "an unregistered proxy has no parent to authorise: {error:#}"
    );

    // And it cannot bring itself to life: `initialize` is the registry's.
    let error = PropAccountProxyContract::new(unregistered_id, fixture.user.clone())
        .methods()
        .initialize()
        .with_contract_ids(&[fixture.deployment.oracle_id, fixture.deployment.pool_id])
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("InvalidRegistry"),
        "only the registry initialises an account: {error:#}"
    );

    // Nor may a stranger register it on the parent's behalf.
    let error = TradeAccountRegistry::new(
        fixture.deployment.registry_id,
        fixture.outsider.clone(),
    )
    .methods()
    .prop_register_contract(unregistered_id, parent, 99)
    .with_contract_ids(&[
        fixture.deployment.oracle_id,
        unregistered_id,
        fixture.deployment.pool_id,
    ])
    .call()
    .await
    .unwrap_err();
    assert!(
        error.to_string().contains("NotParent"),
        "registration is claimed by the parent itself: {error:#}"
    );

    // The parent registers it, and the same account works.
    TradeAccountRegistry::new(fixture.deployment.registry_id, fixture.user.clone())
        .methods()
        .prop_register_contract(unregistered_id, parent, 99)
        .with_contract_ids(&[
            fixture.deployment.oracle_id,
            unregistered_id,
            fixture.deployment.pool_id,
        ])
        .call()
        .await
        .unwrap();
    assert!(
        registry
            .methods()
            .prop_is_valid(unregistered_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    );
    assert_eq!(
        registry
            .methods()
            .prop_parent(unregistered_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        Some(parent)
    );

    // Registering it a second time is refused, so nobody can reparent a live
    // account out from under its owner.
    let error =
        TradeAccountRegistry::new(fixture.deployment.registry_id, fixture.user.clone())
            .methods()
            .prop_register_contract(unregistered_id, parent, 99)
            .with_contract_ids(&[
                fixture.deployment.oracle_id,
                unregistered_id,
                fixture.deployment.pool_id,
            ])
            .call()
            .await
            .unwrap_err();
    assert!(
        error.to_string().contains("AlreadyRegistered"),
        "an account has one parent for life: {error:#}"
    );

    unregistered
        .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();
    assert!(
        fixture
            .deployment
            .pool
            .methods()
            .get_session(unregistered_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
            .is_some()
    );
}

/// `start_session` sweeps the account clean before it opens, and the POOL
/// checks the same thing again on arrival. The second check is not redundant:
/// a session key can reach `open_session` directly, skipping the sweep, and
/// without it a session could be born holding a tier asset the pool never
/// counted as collateral and would later hand out as profit.
#[tokio::test]
async fn the_pool_refuses_to_open_on_an_account_that_is_still_holding() {
    let mut fixture = PropFixture::new().await;

    // A fresh sibling with a session key of its own.
    let parent = Identity::Address(fixture.user.address());
    let sibling = fixture
        .deployment
        .deploy_account(&fixture.user, parent, 7)
        .await
        .unwrap();
    let sibling_id = sibling.contract_id();
    let sibling_account = PropAccountContract::new(sibling_id, fixture.user.clone());
    let expiry = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs()
        + 86_400;
    sibling_account
        .methods()
        .set_session(ParallelSessionArgs {
            nonce: U256::zero(),
            session_id: Identity::Address(fixture.user.address()),
            expiry: Time { unix: expiry },
            contract_ids: vec![],
        })
        .with_contract_ids(&[fixture.deployment.oracle_id])
        .call()
        .await
        .unwrap();

    // Exactly the entry in collateral, plus a stray of the tier's base asset.
    for (asset, amount) in [
        (fixture.collateral_asset, COLLATERAL),
        (fixture.base_asset, 5_000),
    ] {
        fixture
            .deployer
            .force_transfer_to_contract(sibling_id, amount, asset, TxPolicies::default())
            .await
            .unwrap();
    }

    // The session key reaches `open_session` on the pool directly - no sweep.
    let open = CallContractArg {
        contract_id: fixture.deployment.pool_id,
        function_selector: Bytes(fn_selector!(open_session(u64, ProlongPeriod))),
        call_params: CallParams {
            coins: COLLATERAL,
            asset_id: fixture.collateral_asset,
            gas: 30_000_000,
        },
        call_data: Some(Bytes(call_data!(TIER_ID, ProlongPeriod::SixHours))),
    };
    let (user_signature, cosigner_signature, calls) =
        fixture.signed_calls_for(sibling_id, vec![open]).await;
    let error = sibling_account
        .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::EstimateMinimum)
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("AccountNotEmpty"),
        "the pool counts what it was sent, not what the account happens to hold: {error:#}"
    );

    // Through the owner route the sweep runs first and the same account opens
    // cleanly, the stray going home to the parent.
    sibling_account
        .methods()
        .start_session(TIER_ID, COLLATERAL, ProlongPeriod::SixHours)
        .with_contract_ids(&[
            fixture.deployment.oracle_id,
            fixture.deployment.pool_id,
            fixture.deployment.registry_id,
        ])
        .call_params(CallParameters::new(
            COLLATERAL,
            fixture.collateral_asset,
            u64::MAX,
        ))
        .unwrap()
        .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
        .call()
        .await
        .unwrap();
    assert_eq!(
        fixture
            .deployer
            .try_provider()
            .unwrap()
            .get_contract_asset_balance(&sibling_id, &fixture.base_asset)
            .await
            .unwrap(),
        0
    );
}