o2-tools 0.4.4-rc

Reusable tooling for trade account and order book contract interactions on Fuel
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
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
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
//! Buying time: the manual prolongation and the automatic one.
//!
//! The automatic path had no coverage at all - it is the only pool method a
//! keeper calls on a HEALTHY session, so its two gates (`AutoProlongDisabled`
//! and `AutoProlongNotDue`) are the whole thing standing between a scheduled
//! renewal and an unbounded fee drain by anyone with gas.

use super::*;
use crate::prop::AutoProlongChanged;

fn arm_call(fixture: &PropFixture, period: Option<ProlongPeriod>) -> CallContractArg {
    fixture.pool_call(
        fn_selector!(set_auto_prolong(Option<ProlongPeriod>)),
        0,
        AssetId::default(),
        Some(call_data!(period)),
    )
}

fn prolong_period_call(
    fixture: &PropFixture,
    period: ProlongPeriod,
    times: u64,
) -> CallContractArg {
    fixture.pool_call(
        fn_selector!(prolong_session(ProlongPeriod, u64)),
        0,
        AssetId::default(),
        Some(call_data!(period, times)),
    )
}

/// Takes `bps` off every premium the fixture's user pays, prolongations
/// included. The role comes first: pricing favours are their own capability,
/// not a power of the admin's office.
async fn discount_every_premium(fixture: &PropFixture, bps: u64) {
    fixture
        .deployment
        .pool
        .methods()
        .grant_role(
            DISCOUNT_MANAGER_ROLE,
            Identity::Address(fixture.deployer.address()),
        )
        .call()
        .await
        .unwrap();
    fixture
        .deployment
        .pool
        .methods()
        .set_user_discount(
            Identity::Address(fixture.user.address()),
            None,
            Some(UserDiscount {
                discount_bps: bps,
                scope: DiscountScope::AllPremiums,
            }),
        )
        .call()
        .await
        .unwrap();
}

/// Moves the chain to `seconds` before the session's deadline. The fixture's
/// session key is armed for a day from the same instant the session is, so
/// stopping short of the deadline keeps the key alive.
///
/// Callers wanting to be INSIDE the renewal window must pass fewer than
/// `AUTO_PROLONG_WINDOW_SECONDS` (60) - the window is a flat minute now, not
/// the period being renewed - and leave room for the blocks their own calls
/// produce.
async fn approach_deadline(fixture: &PropFixture, seconds: u64) {
    let session = fixture.session().await;
    let provider = fixture.user.try_provider().unwrap().clone();
    let latest = provider.latest_block_time().await.unwrap().unwrap();
    let target = session.expires_at - seconds;
    let jump = target.saturating_sub(latest.timestamp() as u64);
    provider
        .produce_blocks(
            1,
            Some(
                latest
                    .checked_add_signed(chrono::TimeDelta::seconds(jump as i64))
                    .unwrap(),
            ),
        )
        .await
        .unwrap();
}

/// A prolongation the keeper can run unattended has to be cheap to price and
/// impossible to abuse, so only the two SHORT periods may be armed and only
/// when the tier actually sells them. A week or a month would let one keeper
/// call spend a month of premium.
#[tokio::test]
async fn an_auto_extension_can_be_armed_only_on_a_short_period_the_tier_sells() {
    let mut fixture = PropFixture::new().await;

    // Push the deadline out first, so arming below is unambiguously "not due"
    // and cannot fire a prolongation of its own.
    fixture
        .call_account(
            vec![prolong_period_call(&fixture, ProlongPeriod::Week, 1)],
            1,
        )
        .await
        .unwrap();

    for period in [ProlongPeriod::Week, ProlongPeriod::Month] {
        let error = fixture
            .call_account(vec![arm_call(&fixture, Some(period.clone()))], 1)
            .await
            .unwrap_err();
        assert!(
            error.to_string().contains("AutoProlongPeriodInvalid"),
            "{period:?} is too long to hand to a keeper: {error:#}"
        );
    }

    // Six hours IS an automatic period, but this tier gives it away - and a
    // zero fee means "not offered" for prolongation, so it cannot be armed.
    let error = fixture
        .call_account(vec![arm_call(&fixture, Some(ProlongPeriod::SixHours))], 1)
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("PeriodNotOffered"),
        "a term the tier does not sell cannot be renewed: {error:#}"
    );

    // The day is both automatic and priced.
    let response = fixture
        .call_account(vec![arm_call(&fixture, Some(ProlongPeriod::Day))], 1)
        .await
        .unwrap();
    let armed = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<AutoProlongChanged>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(armed.len(), 1);
    assert_eq!(armed[0].period, Some(ProlongPeriod::Day));
    assert_eq!(armed[0].account, fixture.child_id);
    assert!(armed[0].timestamp.unix != 0);
    let prolonged = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionProlonged>(&response.tx_status.receipts)
        .unwrap();
    assert!(
        prolonged.is_empty(),
        "arming outside the window charges nothing"
    );
    assert_eq!(
        fixture.session().await.auto_prolong,
        Some(ProlongPeriod::Day)
    );

    // And disarming is always allowed.
    let response = fixture
        .call_account(vec![arm_call(&fixture, None)], 1)
        .await
        .unwrap();
    let armed = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<AutoProlongChanged>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(armed[0].period, None);
    assert_eq!(fixture.session().await.auto_prolong, None);
}

/// Arming inside the renewal window pays for the renewal on the spot. A user
/// who remembers his subscription with an hour to go gets the same outcome as
/// one who armed a day early and let the keeper run - one call, one fee, one
/// extension.
#[tokio::test]
async fn arming_inside_the_window_extends_and_pays_in_the_same_call() {
    let mut fixture = PropFixture::new().await;

    approach_deadline(&fixture, 30).await;
    let before = fixture.session().await;
    let platform_before = fixture
        .deployer
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();

    let response = fixture
        .call_account(vec![arm_call(&fixture, Some(ProlongPeriod::Day))], 1)
        .await
        .unwrap();

    let armed = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<AutoProlongChanged>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(armed.len(), 1);
    assert_eq!(
        armed[0].expires_at, before.expires_at,
        "the arming event reports the deadline it found, not the one it bought"
    );

    let prolonged = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionProlonged>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(prolonged.len(), 1);
    assert_eq!(prolonged[0].trigger, ProlongTrigger::Auto);
    assert_eq!(prolonged[0].times, 1);
    assert_eq!(prolonged[0].seconds, 86_400);
    assert_eq!(prolonged[0].fee, 6_000);
    assert_eq!(prolonged[0].new_expires_at, before.expires_at + 86_400);

    let after = fixture.session().await;
    assert_eq!(after.expires_at, before.expires_at + 86_400);
    assert_eq!(after.fees_accrued, 6_000);
    assert_eq!(
        after.credit_line,
        before.credit_line - 6_000,
        "the fee shrinks the line one for one"
    );
    assert_eq!(
        fixture
            .deployer
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap()
            - platform_before,
        6_000,
        "and it leaves for the platform inside the same call"
    );
}

/// The keeper's own entry point. It is permissionless - anybody may pay the
/// gas to renew somebody else's session - so the two gates are what stop it
/// becoming a way to spend a stranger's collateral: the user must have armed
/// it, and the deadline must actually be near.
#[tokio::test]
async fn a_keeper_extends_an_armed_session_and_only_once_it_is_due() {
    let mut fixture = PropFixture::new().await;

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

    // Unarmed.
    let error = keeper
        .methods()
        .auto_prolong_session(fixture.child_id)
        .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("AutoProlongDisabled"),
        "renewal is opt-in: {error:#}"
    );

    // Armed a week out, so it is armed but not due.
    fixture
        .call_account(
            vec![prolong_period_call(&fixture, ProlongPeriod::Week, 1)],
            1,
        )
        .await
        .unwrap();
    fixture
        .call_account(vec![arm_call(&fixture, Some(ProlongPeriod::Day))], 1)
        .await
        .unwrap();
    let error = keeper
        .methods()
        .auto_prolong_session(fixture.child_id)
        .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("AutoProlongNotDue"),
        "an armed session is not a standing invitation: {error:#}"
    );

    // Inside the window, the keeper renews it for the user.
    approach_deadline(&fixture, 30).await;
    let before = fixture.session().await;
    let response = keeper
        .methods()
        .auto_prolong_session(fixture.child_id)
        .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
        .call()
        .await
        .unwrap();
    let prolonged = response
        .decode_logs_with_type::<SessionProlonged>()
        .unwrap();
    assert_eq!(prolonged.len(), 1);
    assert_eq!(prolonged[0].trigger, ProlongTrigger::Auto);
    assert_eq!(prolonged[0].new_expires_at, before.expires_at + 86_400);

    // And it cannot be farmed: one renewal moves the deadline out of the
    // window, so the next call is refused until the window comes round again.
    let error = keeper
        .methods()
        .auto_prolong_session(fixture.child_id)
        .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("AutoProlongNotDue"),
        "one call per window, or the fee is a faucet for griefers: {error:#}"
    );
}

/// A prolongation is priced per period and multiplied by `times`, which is the
/// caller's own number - so the multiplication has to be exact in both the fee
/// and the seconds, and the whole thing has to stop before the collateral.
#[tokio::test]
async fn prolonging_charges_times_the_price_and_buys_times_the_term() {
    let mut fixture = PropFixture::new().await;

    let before = fixture.session().await;
    let platform_before = fixture
        .deployer
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();

    // Zero is not a purchase.
    let error = fixture
        .call_account(
            vec![prolong_period_call(&fixture, ProlongPeriod::Day, 0)],
            1,
        )
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("TimesIsZero"),
        "buying nothing is refused rather than logged: {error:#}"
    );

    // A term the tier prices at zero is not on sale, however many are asked
    // for - the entry may include it free, renewal may not.
    let error = fixture
        .call_account(
            vec![prolong_period_call(&fixture, ProlongPeriod::SixHours, 1)],
            1,
        )
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("PeriodNotOffered"),
        "a free term is an entry perk, not a renewal price: {error:#}"
    );

    let response = fixture
        .call_account(
            vec![prolong_period_call(&fixture, ProlongPeriod::Day, 3)],
            1,
        )
        .await
        .unwrap();
    let prolonged = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionProlonged>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(prolonged.len(), 1);
    assert_eq!(prolonged[0].trigger, ProlongTrigger::User);
    assert_eq!(prolonged[0].times, 3);
    assert_eq!(prolonged[0].seconds, 3 * 86_400);
    assert_eq!(prolonged[0].fee, 3 * 6_000);
    assert_eq!(prolonged[0].fees_accrued, 18_000);
    assert_eq!(prolonged[0].new_expires_at, before.expires_at + 3 * 86_400);
    assert_eq!(
        prolonged[0].new_credit_line,
        before.credit_line - 18_000,
        "the line prices off the collateral NET of every fee charged"
    );

    assert_eq!(
        fixture
            .deployer
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap()
            - platform_before,
        18_000
    );

    // Three separate purchases cost exactly what one purchase of three did:
    // the price is flat, so slicing neither saves nor costs.
    let mut expected = 18_000u64;
    for _ in 0..3 {
        fixture
            .call_account(
                vec![prolong_period_call(&fixture, ProlongPeriod::Day, 1)],
                1,
            )
            .await
            .unwrap();
        expected += 6_000;
    }
    let after = fixture.session().await;
    assert_eq!(after.fees_accrued, expected);
    assert_eq!(after.expires_at, before.expires_at + 6 * 86_400);
    assert_eq!(
        fixture
            .deployer
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap()
            - platform_before,
        expected as u128
    );

    // An absurd `times` reports the RULE that refuses it, not an arithmetic
    // failure. The extension is computed after the affordability bound for
    // exactly this reason: `2_592_000 * 8e12` leaves u64, so computing it
    // first would answer `ValueOverflow` where the contract has a named rule.
    let error = fixture
        .call_account(
            vec![prolong_period_call(
                &fixture,
                ProlongPeriod::Month,
                8_000_000_000_000,
            )],
            1,
        )
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("ProlongAboveCollateral"),
        "the bound answers before the arithmetic can overflow: {error:#}"
    );

    // A session may never be charged past what it funded. The bound is
    // STRICT: a session whose fees exactly reached its collateral would exist
    // with no line at all.
    let error = fixture
        .call_account(
            vec![prolong_period_call(&fixture, ProlongPeriod::Month, 3)],
            1,
        )
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("ProlongAboveCollateral"),
        "the platform is never paid out of another session's collateral: {error:#}"
    );
}

// ---------------------------------------------------------------------------
// The renewal at expiry.
// ---------------------------------------------------------------------------

/// Moves the chain `past` seconds beyond the session's deadline. The fixture's
/// session key does not survive a jump of a day or more, so anything after
/// this must go through the KEEPER's route - `expire_session` on the pool -
/// which needs no key.
async fn overshoot_deadline(fixture: &PropFixture, past: u64) {
    let session = fixture.session().await;
    let provider = fixture.user.try_provider().unwrap().clone();
    let latest = provider.latest_block_time().await.unwrap().unwrap();
    let target = session.expires_at + past;
    let jump = target.saturating_sub(latest.timestamp() as u64);
    provider
        .produce_blocks(
            1,
            Some(
                latest
                    .checked_add_signed(chrono::TimeDelta::seconds(jump as i64))
                    .unwrap(),
            ),
        )
        .await
        .unwrap();
}

/// The keeper's forced expiry, from a wallet with no claim on the session.
async fn expire(fixture: &PropFixture) -> Result<CallResponse<()>> {
    Ok(fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .expire_session(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?)
}

/// A session that asked for automatic renewal and can still pay for one has
/// not asked to be absorbed. The window is a single minute now, so a keeper
/// that misses it would otherwise cost the user his seat over a scheduling
/// hiccup - `expire_session` renews him instead.
#[tokio::test]
async fn an_armed_and_funded_session_is_renewed_at_expiry_rather_than_absorbed() {
    let mut fixture = PropFixture::new().await;

    // Armed well outside the window, so nothing fires at arming time.
    fixture
        .call_account(vec![arm_call(&fixture, Some(ProlongPeriod::Day))], 1)
        .await
        .unwrap();
    let before = fixture.session().await;
    assert_eq!(before.auto_prolong, Some(ProlongPeriod::Day));
    assert_eq!(before.fees_accrued, 0);

    let platform_before = fixture
        .deployer
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    overshoot_deadline(&fixture, 1).await;

    let response = expire(&fixture).await.unwrap();
    let prolonged = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionProlonged>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(prolonged.len(), 1);
    assert_eq!(prolonged[0].trigger, ProlongTrigger::Auto);
    assert_eq!(prolonged[0].times, 1);
    assert_eq!(prolonged[0].seconds, 86_400);
    assert_eq!(prolonged[0].fee, 6_000);

    let closed = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionClosed>(&response.tx_status.receipts)
        .unwrap();
    assert!(
        closed.is_empty(),
        "the expiry call renewed the session; nothing was settled"
    );
    let seized = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionSeized>(&response.tx_status.receipts)
        .unwrap();
    assert!(seized.is_empty(), "and no basket was routed anywhere");

    let after = fixture.session().await;
    assert_eq!(
        after.session_id, before.session_id,
        "the same session lives on"
    );
    assert_eq!(after.fees_accrued, 6_000);
    assert_eq!(after.collateral, before.collateral);
    assert_eq!(after.auto_prolong, Some(ProlongPeriod::Day));
    assert_eq!(
        after.expires_at,
        before.expires_at + 86_400,
        "one period, measured from the deadline it replaces"
    );
    assert_eq!(
        prolonged[0].new_expires_at, after.expires_at,
        "the event carries the deadline the queue must re-key to"
    );
    assert_eq!(
        fixture
            .deployer
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap()
            - platform_before,
        6_000,
        "and the renewal is paid for like any other"
    );
}

/// The renewal is decided BEFORE `absorb`, and this is why. `absorb` drives
/// `pool_cleanup` through the account before it reads the expiry gate, so a
/// renewal decided inside it would keep the user's seat and cancel his entire
/// book on the way.
///
/// The keeper is HANDED the resting order here, deliberately. With an empty
/// cleanup list the rejected design would have failed on `BookNotDrained`
/// instead - the right outcome for the wrong reason, and no evidence about
/// cancellation at all. Naming the order is what makes the test discriminate:
/// under the rejected design it would be cancelled, and the assertion below
/// would see the lock gone.
#[tokio::test]
async fn the_renewal_at_expiry_leaves_the_users_resting_orders_alone() {
    let mut fixture = PropFixture::new().await;

    // Draw and park the cash in an unfilled order, then arm.
    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();
    fixture
        .call_account(vec![arm_call(&fixture, Some(ProlongPeriod::Day))], 1)
        .await
        .unwrap();

    let locked = fixture
        .order_book
        .order_book
        .methods()
        .get_total_balance_of(Identity::ContractId(fixture.child_id))
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value;
    assert_ne!(locked, (0, 0), "the account has something resting");

    overshoot_deadline(&fixture, 1).await;
    let orders = fixture
        .order_book
        .order_book
        .methods()
        .get_orders_at_price(crate::order_book_deploy::Side::Buy, 1_000_000)
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value;
    let cleanup = crate::prop::PropOrderBookCleanup {
        order_book: fixture.order_book.contract_id,
        order_ids: orders
            .into_iter()
            .filter(|o| o.trader_id == Identity::ContractId(fixture.child_id))
            .map(|o| o.order_id)
            .collect(),
    };
    assert_eq!(
        cleanup.order_ids.len(),
        1,
        "the keeper is handed a real order"
    );

    fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .expire_session(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();

    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,
        locked,
        "a renewed session keeps its book exactly as it was, even when the \
         caller handed the pool an order to cancel"
    );
    assert_eq!(
        fixture.session().await.drawn_quote,
        1_000_000,
        "and its draw"
    );
}

/// A late renewal buys every elapsed period and is billed for all of them.
///
/// The deadline anchors on the one it REPLACES, exactly as a user's own
/// `prolong_session` does, so the term the session bought is the term it paid
/// for and the gap the keeper slept through is not a discount. Being late is
/// therefore never cheaper than being on time - which it would be if the
/// renewal restarted the clock at `now` for a single fee.
///
/// The count is what keeps the path from being drained, too: buying enough
/// periods to clear `now` lands the deadline strictly in the future, so the
/// next permissionless call finds a live session instead of another fee.
#[tokio::test]
async fn a_late_renewal_buys_every_elapsed_period_and_is_billed_for_all_of_them() {
    let mut fixture = PropFixture::new().await;

    fixture
        .call_account(vec![arm_call(&fixture, Some(ProlongPeriod::Day))], 1)
        .await
        .unwrap();
    let before = fixture.session().await;

    // Three whole periods past the deadline: a keeper outage, not a hiccup.
    // Three elapsed plus one to carry the session forward is four.
    overshoot_deadline(&fixture, 3 * 86_400).await;
    let response = expire(&fixture).await.unwrap();
    let prolonged = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionProlonged>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(prolonged.len(), 1);
    assert_eq!(prolonged[0].times, 4);
    assert_eq!(prolonged[0].seconds, 4 * 86_400);
    assert_eq!(prolonged[0].fee, 24_000, "four periods at the tier's price");

    let chain_now = fixture
        .user
        .try_provider()
        .unwrap()
        .latest_block_time()
        .await
        .unwrap()
        .unwrap()
        .timestamp() as u64;
    let after = fixture.session().await;
    assert_eq!(
        after.expires_at,
        before.expires_at + 4 * 86_400,
        "the term extends the OLD deadline, not the moment the keeper woke up"
    );
    assert!(
        after.expires_at > chain_now,
        "and still clears now, or the seat could be charged again at once: {} vs {chain_now}",
        after.expires_at
    );
    assert!(
        after.expires_at <= chain_now + 86_400,
        "with only the unelapsed remainder left to run"
    );
    assert_eq!(after.fees_accrued, 24_000);

    // The drain the count prevents: a second call finds a live session and is
    // turned away, so nothing is charged twice.
    let error = expire(&fixture).await.unwrap_err();
    assert!(
        error.to_string().contains("NotExpired"),
        "a renewed session is live, so nobody can charge it again: {error:#}"
    );
    assert_eq!(fixture.session().await.fees_accrued, 24_000);
}

/// A session that cannot cover the whole bill still pays for the time it
/// held: it is charged every period it CAN cover, and then absorbed.
///
/// Lapsing must never be the cheap way out of a fee. Forgiving the bill
/// outright would mean a session near its collateral floor was better off
/// letting the deadline pass than renewing - it would keep the difference and
/// the pool would carry the elapsed term for nothing.
///
/// The partial charge is also capped so the term still ends BEFORE now: the
/// charge moves `expires_at`, and `absorb` demands an expired session, so a
/// term landing exactly on `now` would take the fee and then revert the very
/// settlement it was collected during.
#[tokio::test]
async fn a_session_that_cannot_cover_the_gap_pays_for_what_it_can_and_is_absorbed() {
    let mut fixture = PropFixture::new().await;

    // Armed, then charged to 1_980_000 of its 2_000_000: 19_999 of headroom
    // is left under the strict bound, which buys three more periods at 6_000
    // and not a fourth.
    fixture
        .call_account(
            vec![
                arm_call(&fixture, Some(ProlongPeriod::Day)),
                prolong_period_call(&fixture, ProlongPeriod::Day, 330),
            ],
            1,
        )
        .await
        .unwrap();
    let starved = fixture.session().await;
    assert_eq!(starved.fees_accrued, 1_980_000);

    // Ten periods late, so eleven are wanted and only three are payable.
    overshoot_deadline(&fixture, 10 * 86_400).await;
    let response = expire(&fixture).await.unwrap();

    let prolonged = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionProlonged>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(prolonged.len(), 1, "the partial charge is a real charge");
    assert_eq!(prolonged[0].times, 3);
    assert_eq!(prolonged[0].fee, 18_000);

    let closed = fixture.closed_event(&response);
    assert_eq!(
        closed.reason,
        SettlementReason::Expiry,
        "charged for what it could, then absorbed in the same call"
    );
    assert_eq!(
        closed.fees_accrued, 1_998_000,
        "the three periods it could pay for are on the settlement"
    );
    assert_eq!(
        closed.user_net, 2_000,
        "and only the unbillable remainder comes back"
    );
    assert!(
        fixture
            .deployment
            .pool
            .methods()
            .get_session(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
            .is_none(),
        "the seat is gone all the same"
    );
}

/// The renewal is a courtesy the collateral has to cover. A session that
/// cannot pay for even ONE period is absorbed exactly as it was before,
/// rather than reverting the keeper's call and leaving the seat stuck open -
/// and with nothing charged on the way out, because there was nothing it
/// could afford to be charged.
#[tokio::test]
async fn an_armed_session_that_cannot_pay_the_renewal_is_absorbed_as_before() {
    let mut fixture = PropFixture::new().await;

    // Armed, then charged to within one fee of its collateral: 333 x 6_000 is
    // 1_998_000 against 2_000_000 funded, so the NEXT 6_000 cannot be carried.
    fixture
        .call_account(
            vec![
                arm_call(&fixture, Some(ProlongPeriod::Day)),
                prolong_period_call(&fixture, ProlongPeriod::Day, 333),
            ],
            1,
        )
        .await
        .unwrap();
    let starved = fixture.session().await;
    assert_eq!(starved.fees_accrued, 1_998_000);
    assert_eq!(starved.auto_prolong, Some(ProlongPeriod::Day));

    overshoot_deadline(&fixture, 1).await;
    let response = expire(&fixture).await.unwrap();

    let closed = fixture.closed_event(&response);
    assert_eq!(closed.reason, SettlementReason::Expiry);
    assert_eq!(closed.fees_accrued, 1_998_000);
    assert_eq!(
        closed.user_net, 2_000,
        "what the collateral had left after the premiums it did pay"
    );
    assert!(
        fixture
            .deployment
            .pool
            .methods()
            .get_session(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
            .is_none(),
        "the seat is gone, as it would have been before this change"
    );
}

/// The count the renewal buys is priced at the user's DISCOUNTED bill, not at
/// list — a discounted session can afford more periods, and must get them.
///
/// This is the one that catches the count and the charge drifting apart.
/// `affordable_periods` inverts the bill to decide how many periods fit the
/// collateral; `commit_prolongation` then charges for them. If the inversion
/// judged list price while the charge took the discount, this session would
/// be told it could afford three periods when it could afford five — and
/// three does not clear the deadline, so it would be part-charged and
/// ABSORBED. Losing a seat that could pay is the failure being ruled out, and
/// only a discount steep enough to change the answer can rule it out.
#[tokio::test]
async fn a_discounted_session_is_renewed_on_the_count_its_discount_buys() {
    let mut fixture = PropFixture::new().await;

    // Armed, then charged at LIST to 1_980_000 of its 2_000_000 — the
    // discount lands afterwards, so the headroom is a round 19_999.
    fixture
        .call_account(
            vec![
                arm_call(&fixture, Some(ProlongPeriod::Day)),
                prolong_period_call(&fixture, ProlongPeriod::Day, 330),
            ],
            1,
        )
        .await
        .unwrap();
    let before = fixture.session().await;
    assert_eq!(before.fees_accrued, 1_980_000);

    // Half off. 19_999 of headroom buys three periods at 6_000 and six at
    // 3_000, and the keeper is about to need five.
    discount_every_premium(&fixture, 5_000).await;

    overshoot_deadline(&fixture, 4 * 86_400).await;
    let response = expire(&fixture).await.unwrap();

    let prolonged = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionProlonged>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(prolonged.len(), 1);
    assert_eq!(
        prolonged[0].times, 5,
        "five periods — the count list price would have refused"
    );
    assert_eq!(
        prolonged[0].fee, 15_000,
        "and billed at the discount that allowed them"
    );

    let closed = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionClosed>(&response.tx_status.receipts)
        .unwrap();
    assert!(
        closed.is_empty(),
        "the seat survives: judging this at list price would have absorbed it"
    );
    let after = fixture.session().await;
    assert_eq!(after.expires_at, before.expires_at + 5 * 86_400);
    assert_eq!(after.fees_accrued, 1_995_000);
}

/// A fully forgiven premium renews at any count, however late and however
/// little collateral is left.
///
/// `discount_bps` may be `BPS` — a 100% grant — which makes the multiplier
/// the inversion divides by ZERO. The search this replaced never divided, so
/// it never had to care; the closed form does, and this is the case that
/// proves the guard is a real branch rather than a defensive one.
///
/// The session here is the same one
/// `an_armed_session_that_cannot_pay_the_renewal_is_absorbed_as_before`
/// absorbs: 333 premiums deep, 1_999 of headroom, unable to buy a single
/// period at list. Free, it keeps its seat.
#[tokio::test]
async fn a_wholly_forgiven_premium_renews_a_session_that_could_not_pay_a_cent() {
    let mut fixture = PropFixture::new().await;

    fixture
        .call_account(
            vec![
                arm_call(&fixture, Some(ProlongPeriod::Day)),
                prolong_period_call(&fixture, ProlongPeriod::Day, 333),
            ],
            1,
        )
        .await
        .unwrap();
    let before = fixture.session().await;
    assert_eq!(before.fees_accrued, 1_998_000);

    discount_every_premium(&fixture, 10_000).await;

    overshoot_deadline(&fixture, 3 * 86_400).await;
    let response = expire(&fixture).await.unwrap();

    let prolonged = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionProlonged>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(prolonged.len(), 1);
    assert_eq!(
        prolonged[0].times, 4,
        "the whole gap, because none of it costs anything"
    );
    assert_eq!(prolonged[0].fee, 0);

    let after = fixture.session().await;
    assert_eq!(after.expires_at, before.expires_at + 4 * 86_400);
    assert_eq!(
        after.fees_accrued, 1_998_000,
        "a free renewal accrues nothing, so the line does not move either"
    );
    assert_eq!(after.credit_line, before.credit_line);
}

/// The renewal must never become the reason a session cannot be closed.
///
/// `pay_fee` ends the renewal with
/// `require(this_balance >= fee, InsufficientInventory)`, and the pool's quote
/// float is shared: `draw` and `borrow` can take it below any single session's
/// fee. Without a pre-flight the keeper's `expire_session` would REVERT there
/// - and `absorb` would have succeeded, because `pool_sweep` pulls the
/// account's own basket in before any payout, so the very sweep that refills
/// the float is what the revert blocks.
///
/// Reaching the state needs a session whose draw is most of the pool: with the
/// fixture's own tier the float can never fall below one fee, because a
/// session's collateral sits IN the pool and the line is capped at twice it.
/// A wide tier breaks that - the line is 5x the collateral, so the draw can
/// carry the float away.
#[tokio::test]
async fn a_renewal_the_pool_cannot_fund_absorbs_instead_of_reverting() {
    let mut fixture = PropFixture::new().await;

    let (child_id, account, collateral) = starved_pool_session(&mut fixture, 1_000).await;
    assert_eq!(
        fixture.pool_balance(fixture.collateral_asset).await,
        1_000,
        "the pool now holds less than the 6_000 renewal fee"
    );

    // Past the deadline. The session is armed and can AFFORD the fee out of
    // its own collateral - but the pool cannot pay it out.
    overshoot_child_deadline(&fixture, child_id, 1).await;

    let response = fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .expire_session(child_id, vec![])
        .with_contracts(&[
            &account,
            &fixture.deployment.oracle,
            &fixture.order_book.order_book,
            &fixture.deployment.price_feed,
        ])
        .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
        .call()
        .await
        .unwrap();

    let closed = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionClosed>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(
        closed.len(),
        1,
        "the session was absorbed, not left stranded"
    );
    assert_eq!(closed[0].reason, SettlementReason::Expiry);
    // And the absorption is CLEAN: the drawn cash was sitting on the account,
    // so the sweep hands it straight back and the parent is paid in full.
    //
    // That is the whole shape of the bug this test exists for. The float was
    // genuinely under the fee at the moment `expire_session` was called - the
    // renewal would have reverted `InsufficientInventory` there - and the
    // money that makes the absorption work only arrives during the sweep,
    // AFTER the point the renewal would have failed.
    assert_eq!(closed[0].bad_debt, 0);
    assert_eq!(closed[0].user_net, collateral);
    let prolonged = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionProlonged>(&response.tx_status.receipts)
        .unwrap();
    assert!(
        prolonged.is_empty(),
        "a pool that cannot pay the fee must not have renewed"
    );
    assert!(
        fixture
            .deployment
            .pool
            .methods()
            .get_session(child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
            .is_none()
    );
}

/// The FLOAT caps the partial charge too, not just the whole renewal.
///
/// A session can be rich enough to buy every period it slept through and
/// still be told it may only have two, because the pool's quote float is what
/// the fee is paid OUT of and a draw can carry that away. The collateral
/// bound and the float bound are separate ceilings and the lower one wins;
/// with the fixture's own tier only the collateral one is ever reachable, so
/// without this the float's half of `affordable_periods` is never exercised
/// on the partial path at all.
#[tokio::test]
async fn the_pools_float_caps_the_partial_charge_before_the_collateral_does() {
    let mut fixture = PropFixture::new().await;

    // Two periods' worth of float and a thousand to spare, against a session
    // whose 40_000_000 of collateral could pay for hundreds.
    let (child_id, account, _collateral) =
        starved_pool_session(&mut fixture, 13_000).await;

    // Four whole periods late, so five are wanted and the float allows two.
    overshoot_child_deadline(&fixture, child_id, 4 * 86_400).await;

    let response = fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .expire_session(child_id, vec![])
        .with_contracts(&[
            &account,
            &fixture.deployment.oracle,
            &fixture.order_book.order_book,
            &fixture.deployment.price_feed,
        ])
        .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
        .call()
        .await
        .unwrap();

    let prolonged = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionProlonged>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(prolonged.len(), 1, "what the float could fund was charged");
    assert_eq!(
        prolonged[0].times, 2,
        "two periods — the collateral would have carried all five"
    );
    assert_eq!(prolonged[0].fee, 12_000);

    let closed = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionClosed>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(closed.len(), 1, "and the rest of the gap it could not fund");
    assert_eq!(closed[0].reason, SettlementReason::Expiry);
    assert_eq!(closed[0].bad_debt, 0);
    assert!(
        fixture
            .deployment
            .pool
            .methods()
            .get_session(child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
            .is_none()
    );
}

/// Opens an armed session on a tier whose line dwarfs its entry ticket and
/// draws the pool's quote float down to `float_left`.
///
/// The fixture's own tier cannot reach this state: a session's collateral
/// sits IN the pool and the line is capped at twice it, so the float can
/// never fall below one fee. A 5x line breaks that - the draw can carry the
/// float away. Returns the account and the collateral it was funded with.
async fn starved_pool_session(
    fixture: &mut PropFixture,
    float_left: u64,
) -> (ContractId, PropAccountContract<Wallet>, u64) {
    // 200_000_000 at 5x: ticket 40_000_000, k 160_000_000.
    let wide = TierParams {
        line: 200_000_000,
        leverage: 5,
        duration: 64_800,
        maintenance_bps: 250,
        open_buffer_bps: 375,
        liq_price_factor: 9_900,
        prolong_fee: [0, 6_000, 76_000, 738_000],
        max_credit_line_bps: 20_000,
        max_price_age: u64::MAX,
        open_fee: 0,
        profit_share_bps: 1_000,
        price_band_bps: 1_000,
    };
    let tier_id = 31;
    fixture
        .deployment
        .pool
        .methods()
        .publish_tier_version(tier_id, wide, vec![fixture.order_book.contract_id])
        .with_contract_ids(&[
            fixture.order_book.contract_id,
            fixture.deployment.price_feed_id,
        ])
        .call()
        .await
        .unwrap();

    let parent = Identity::Address(fixture.user.address());
    let child = fixture
        .deployment
        .deploy_account(&fixture.user, parent, 31)
        .await
        .unwrap();
    let child_id = child.contract_id();
    let account = PropAccountContract::new(child_id, fixture.user.clone());
    let key_expiry = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs()
        + 86_400;
    account
        .methods()
        .set_session(ParallelSessionArgs {
            nonce: U256::zero(),
            session_id: Identity::Address(fixture.user.address()),
            expiry: Time { unix: key_expiry },
            contract_ids: vec![],
        })
        .with_contract_ids(&[fixture.deployment.oracle_id])
        .call()
        .await
        .unwrap();

    let collateral = 40_000_000u64;
    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,
        ])
        .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
        .call()
        .await
        .unwrap();

    // Arm the renewal, then draw the pool's quote float down to the target.
    let float = fixture.pool_balance(fixture.collateral_asset).await;
    let draw = float - float_left;
    let calls = vec![
        fixture.pool_call(
            fn_selector!(set_auto_prolong(Option<ProlongPeriod>)),
            0,
            AssetId::default(),
            Some(call_data!(Some(ProlongPeriod::Day))),
        ),
        fixture.pool_call(
            fn_selector!(draw(u64)),
            0,
            AssetId::default(),
            Some(call_data!(draw)),
        ),
    ];
    let signed = fixture.signed_calls_for(child_id, calls).await;
    account
        .methods()
        .call_contracts(signed.0, signed.1, signed.2)
        .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(2))
        .call()
        .await
        .unwrap();
    assert_eq!(
        fixture.pool_balance(fixture.collateral_asset).await,
        float_left,
        "the draw left the pool exactly the float the caller asked for"
    );

    (child_id, account, collateral)
}

/// Moves the chain `past` seconds beyond a NAMED child's deadline, for the
/// sessions that do not belong to the fixture's own account.
async fn overshoot_child_deadline(fixture: &PropFixture, child: ContractId, past: u64) {
    let session = fixture
        .deployment
        .pool
        .methods()
        .get_session(child)
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value
        .unwrap();
    let provider = fixture.user.try_provider().unwrap().clone();
    let latest = provider.latest_block_time().await.unwrap().unwrap();
    let jump = (session.expires_at + past).saturating_sub(latest.timestamp() as u64);
    provider
        .produce_blocks(
            1,
            Some(
                latest
                    .checked_add_signed(chrono::TimeDelta::seconds(jump as i64))
                    .unwrap(),
            ),
        )
        .await
        .unwrap();
}