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
//! Historical refundable entry costs and stale-price compatibility.
//! New refundable tiers cannot be published; these tests seed historical records.
//!
//! Both need a tier the fixture does not seed - a priced entry for the
//! first, a finite `max_price_age` for the second - so each test brings its
//! own tier and its own account and leaves the fixture's session alone.

use super::*;

/// Seed a historical tier variant; no legacy publisher is available.
async fn seed_variant(
    fixture: &PropFixture,
    tier_id: u64,
    params: TierParams,
) -> TierParams {
    seed_legacy_tier(
        &fixture.deployment,
        tier_id,
        params.clone(),
        vec![fixture.order_book.contract_id],
    )
    .await
    .unwrap();
    params
}

fn variant(open_fee: u64, max_price_age: u64) -> TierParams {
    TierParams {
        line: LINE,
        leverage: 5,
        duration: 86_400,
        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,
        open_fee,
        profit_share_bps: 1_000,
        price_band_bps: 1_000,
    }
}

/// A registered sibling account with a session key armed, and no session.
async fn armed_sibling(
    fixture: &PropFixture,
    index: u64,
) -> (ContractId, PropAccountContract<Wallet>) {
    let parent = Identity::Address(fixture.user.address());
    let child = fixture
        .deployment
        .deploy_account(&fixture.user, parent, index)
        .await
        .unwrap();
    let child_id = child.contract_id();
    let account = PropAccountContract::new(child_id, fixture.user.clone());
    let 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: expiry },
            contract_ids: vec![],
        })
        .with_contract_ids(&[fixture.deployment.oracle_id])
        .call()
        .await
        .unwrap();
    (child_id, account)
}

async fn open_on(
    fixture: &PropFixture,
    account: &PropAccountContract<Wallet>,
    tier_id: u64,
    amount: u64,
) -> Result<CallResponse<()>> {
    Ok(account
        .methods()
        .start_session(tier_id, amount, ProlongPeriod::SixHours)
        .call_params(CallParameters::new(
            amount,
            fixture.collateral_asset,
            u64::MAX,
        ))
        .unwrap()
        // `with_contracts`, not `with_contract_ids`: a refused open has to
        // report WHICH rule refused it, and the name comes from the pool's own
        // log decoder.
        .with_contracts(&[
            &fixture.deployment.oracle,
            &fixture.deployment.pool,
            &fixture.deployment.registry,
        ])
        .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
        .call()
        .await?)
}

// ---------------------------------------------------------------------------
// The price of the door.
// ---------------------------------------------------------------------------

/// A tier sells a seat AND a first term, and both are charged out of the
/// collateral posted at the door. Two bounds sit on that: the entry ticket the
/// tier's leverage implies, and the requirement that what is left after the
/// premium still clears the FREEZE line - a session that opens already unable
/// to place an order has bought nothing.
#[tokio::test]
async fn an_entry_the_premium_would_leave_frozen_is_refused_at_the_door() {
    let fixture = PropFixture::new().await;

    // 1_700_000 of premium against a 2_000_000 entry ticket and a 375_000
    // freeze buffer: the ticket alone no longer covers both.
    let tier_id = 21;
    seed_variant(&fixture, tier_id, variant(1_700_000, u64::MAX)).await;
    let (child_id, account) = armed_sibling(&fixture, 21).await;

    // Below the tier's own entry ticket.
    let error = open_on(&fixture, &account, tier_id, 1_999_999)
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("CollateralTooSmall"),
        "the entry ticket is `line / leverage`: {error:#}"
    );

    // Exactly the ticket - but the premium eats into the freeze buffer, so the
    // session would be born unable to act.
    let error = open_on(&fixture, &account, tier_id, 2_000_000)
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("SessionUnusableAtOpen"),
        "a session must clear the freeze line at birth, not merely survive: {error:#}"
    );

    // A tier that was never published. The account resolves the version before
    // it forwards anything, so the entry never reaches the pool at all.
    assert!(
        fixture
            .deployment
            .pool
            .methods()
            .current_tier_version(4_242)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
            .is_none()
    );
    assert!(
        open_on(&fixture, &account, 4_242, 2_100_000).await.is_err(),
        "there is no default tier"
    );

    // Enough to cover the premium AND the buffer, and it opens - on a line
    // priced off the collateral NET of the premium, so the premium never buys
    // borrowing power.
    let platform_before = fixture
        .deployer
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    let response = open_on(&fixture, &account, tier_id, 2_100_000)
        .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].open_fee, 1_700_000);
    assert_eq!(opened[0].fees_accrued, 1_700_000);
    assert_eq!(
        opened[0].collateral, 2_100_000,
        "the collateral stays GROSS; the fee is recorded, not deducted"
    );
    assert_eq!(
        opened[0].credit_line,
        8_000_000 + (2_100_000 - 1_700_000),
        "the line prices off the collateral net of the premium"
    );
    assert_eq!(
        fixture
            .deployer
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap()
            - platform_before,
        1_700_000,
        "and the premium leaves for the platform inside the opening call"
    );

    // The session is usable: it clears the freeze line with room to act.
    let lines = fixture
        .deployment
        .pool
        .methods()
        .get_session_lines(child_id)
        .with_contract_ids(&[
            child_id,
            fixture.order_book.contract_id,
            fixture.deployment.price_feed_id,
        ])
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value;
    assert!(lines.positive - lines.negative >= lines.freeze);
}

// ---------------------------------------------------------------------------
// A feed that goes quiet.
// ---------------------------------------------------------------------------

/// Every path that MARKS something reads the feed, and a mark from an hour ago
/// is not a mark. So a quiet feed stops the marked paths - including the
/// keeper's seizure, which is the right answer: nobody should be liquidated
/// against a price nobody is standing behind.
///
/// The escape hatch is the UNMARKED half: the in-kind repayment, the quote
/// return and the netting all run regardless, and a close whose residual is
/// pure CASH needs no price either. That is the exit this test walks - it
/// repays the asset in kind first, on purpose.
///
/// That is NOT the whole story, and the limit is the point of the test below
/// it: a close that still has a POSITION to value reads the feed like
/// everything else and stops with the rest. See
/// `a_quiet_feed_strands_a_session_that_still_holds_the_asset`.
#[tokio::test]
async fn a_stale_feed_stops_the_marked_paths_and_leaves_the_cash_exit_open() {
    let mut fixture = PropFixture::new().await;

    let tier_id = 22;
    seed_variant(&fixture, tier_id, variant(0, 3_600)).await;
    let (child_id, account) = armed_sibling(&fixture, 22).await;
    open_on(&fixture, &account, tier_id, COLLATERAL)
        .await
        .unwrap();

    let quantity = 500_000_000u64;
    let borrow = CallContractArg {
        contract_id: fixture.deployment.pool_id,
        function_selector: Bytes(fn_selector!(borrow(AssetId, u64))),
        call_params: CallParams {
            coins: 0,
            asset_id: AssetId::default(),
            gas: 30_000_000,
        },
        call_data: Some(Bytes(call_data!(fixture.base_asset, quantity))),
    };

    let submit = |fixture: &PropFixture,
                  account: &PropAccountContract<Wallet>,
                  signed: (Signature, Signature, ParallelMultiCallContractArgs),
                  outputs: usize| {
        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(outputs))
    };

    // The harness publishes far behind the chain, so under a one-hour bound
    // the standing price is already too old to lend against.
    let signed = fixture
        .signed_calls_for(child_id, vec![borrow.clone()])
        .await;
    let error = submit(&fixture, &account, signed, 1)
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("PriceStale"),
        "the loan cap refuses to price a debt off a stale mark: {error:#}"
    );

    // A fresh observation, and the same borrow lands.
    let chain_now = fixture
        .user
        .try_provider()
        .unwrap()
        .latest_block_time()
        .await
        .unwrap()
        .unwrap()
        .timestamp() as u64;
    fixture
        .deployment
        .price_feed
        .methods()
        .publish_prices(vec![PriceInput {
            asset: fixture.base_asset,
            bid: 2_000_000_000_000_000_000u64.into(),
            ask: 2_000_000_000_000_000_000u64.into(),
            timestamp: chain_now,
        }])
        .call()
        .await
        .unwrap();
    let signed = fixture.signed_calls_for(child_id, vec![borrow]).await;
    submit(&fixture, &account, signed, 1).call().await.unwrap();
    assert_eq!(
        fixture
            .deployment
            .pool
            .methods()
            .get_debt(child_id, fixture.base_asset)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        quantity
    );

    // Two hours of silence.
    let provider = fixture.user.try_provider().unwrap().clone();
    let latest = provider.latest_block_time().await.unwrap().unwrap();
    provider
        .produce_blocks(
            1,
            Some(
                latest
                    .checked_add_signed(chrono::TimeDelta::seconds(7_200))
                    .unwrap(),
            ),
        )
        .await
        .unwrap();

    // The keeper cannot seize against a price nobody is standing behind.
    let error = fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .liquidate(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_err();
    assert!(
        error.to_string().contains("PriceStale"),
        "a seizure needs a live mark: {error:#}"
    );

    let error = fixture
        .deployment
        .pool
        .methods()
        .force_close_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_err();
    assert!(
        error.to_string().contains("PriceStale"),
        "a permissioned closure also needs a live mark: {error:#}"
    );
    assert_eq!(
        fixture
            .deployer
            .try_provider()
            .unwrap()
            .get_contract_asset_balance(&child_id, &fixture.base_asset)
            .await
            .unwrap(),
        quantity
    );
    assert!(
        fixture
            .deployment
            .pool
            .methods()
            .has_session(child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    );

    // Nor can the read surface pretend it has one.
    let error = fixture
        .deployment
        .pool
        .methods()
        .get_session_lines(child_id)
        .with_contract_ids(&[
            child_id,
            fixture.order_book.contract_id,
            fixture.deployment.price_feed_id,
        ])
        .simulate(Execution::state_read_only())
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("PriceStale"),
        "the health read fails closed rather than serving an old number: {error:#}"
    );

    // Nor can the user convert the debt at a mark the pool cannot trust.
    let convert = CallContractArg {
        contract_id: fixture.deployment.pool_id,
        function_selector: Bytes(fn_selector!(repay_base_from_collateral(AssetId, u64))),
        call_params: CallParams {
            coins: 0,
            asset_id: AssetId::default(),
            gas: 30_000_000,
        },
        call_data: Some(Bytes(call_data!(fixture.base_asset, quantity))),
    };
    let signed = fixture.signed_calls_for(child_id, vec![convert]).await;
    let error = submit(&fixture, &account, signed, 1)
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("PriceStale"),
        "the marked conversion stops with the rest: {error:#}"
    );

    // But the unmarked way out is untouched: repay the asset itself and walk.
    let repay = CallContractArg {
        contract_id: fixture.deployment.pool_id,
        function_selector: Bytes(fn_selector!(repay())),
        call_params: CallParams {
            coins: quantity,
            asset_id: fixture.base_asset,
            gas: 30_000_000,
        },
        call_data: None,
    };
    let signed = fixture.signed_calls_for(child_id, vec![repay]).await;
    submit(&fixture, &account, signed, 0).call().await.unwrap();

    let parent_before = fixture
        .user
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    account
        .methods()
        .close_session(Vec::<crate::prop::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();
    assert_eq!(
        fixture
            .user
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap()
            - parent_before,
        COLLATERAL as u128,
        "a quiet feed must never hold a debt-free user inside a session"
    );
}

/// The limit of the escape hatch, and the wedge it leaves behind.
///
/// `settle` values the closing basket even for a VOLUNTARY close: `event_legs`
/// falls through to `portfolio_legs`, which prices every tier asset the
/// account holds. So a session with a position still open is not merely
/// un-liquidatable during a feed outage - it cannot leave under its own power
/// either. All three exits stop on the same read, and the collateral sits
/// there until a publisher comes back.
///
/// Worse, the session does not have to have TRADED the asset. `holdings`
/// reads the account's raw balance, and a prop account is an ordinary contract
/// anyone can send to - so an outsider can put a session in this state with a
/// one-unit gift of any asset its tier admits.
#[tokio::test]
async fn a_quiet_feed_strands_a_session_that_still_holds_the_asset() {
    let fixture = PropFixture::new().await;

    // A tier that expects a fresh mark. The harness's publish clock runs far
    // behind the chain, so the standing base price is already too old for it.
    let tier_id = 23;
    seed_variant(&fixture, tier_id, variant(0, 3_600)).await;
    let (child_id, account) = armed_sibling(&fixture, 23).await;
    open_on(&fixture, &account, tier_id, COLLATERAL)
        .await
        .unwrap();

    // Cash only: the close needs no mark and works, exactly as the test above
    // promises.
    assert_eq!(
        fixture
            .deployer
            .try_provider()
            .unwrap()
            .get_contract_asset_balance(&child_id, &fixture.base_asset)
            .await
            .unwrap(),
        0
    );

    // One unit of a tier asset, from a stranger. The session never traded it,
    // owes nothing on it and cannot refuse it.
    fixture
        .deployer
        .force_transfer_to_contract(
            child_id,
            1,
            fixture.base_asset,
            TxPolicies::default(),
        )
        .await
        .unwrap();

    // Now every exit needs a price for it, and there is not one.
    let error = account
        .methods()
        .close_session(Vec::<crate::prop::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("PriceStale"),
        "a held position is valued even on a voluntary close: {error:#}"
    );

    let keeper = fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone());
    let error = keeper
        .methods()
        .liquidate(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_err();
    assert!(
        error.to_string().contains("PriceStale"),
        "the keeper stops on the same read: {error:#}"
    );

    // Not even the deadline frees it. `expire_session` checks the cheap thing
    // first, so before the deadline it reports `NotExpired` rather than the
    // price - but once the clock passes it, it needs the same mark as the rest.
    let error = keeper
        .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_err();
    assert!(
        error.to_string().contains("NotExpired"),
        "the deadline is checked before the walk: {error:#}"
    );

    let provider = fixture.user.try_provider().unwrap().clone();
    let expires_at = fixture
        .deployment
        .pool
        .methods()
        .get_session(child_id)
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value
        .unwrap()
        .expires_at;
    let latest = provider.latest_block_time().await.unwrap().unwrap();
    let jump = expires_at.saturating_sub(latest.timestamp() as u64) + 1;
    provider
        .produce_blocks(
            1,
            Some(
                latest
                    .checked_add_signed(chrono::TimeDelta::seconds(jump as i64))
                    .unwrap(),
            ),
        )
        .await
        .unwrap();

    let error = keeper
        .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_err();
    assert!(
        error.to_string().contains("PriceStale"),
        "past the deadline it stops on the mark too, so nobody can free it: {error:#}"
    );

    // The wedge is not permanent - it lasts exactly as long as the outage. One
    // fresh observation and the keeper can finally do its job.
    let chain_now = fixture
        .user
        .try_provider()
        .unwrap()
        .latest_block_time()
        .await
        .unwrap()
        .unwrap()
        .timestamp() as u64;
    fixture
        .deployment
        .price_feed
        .methods()
        .publish_prices(vec![PriceInput {
            asset: fixture.base_asset,
            bid: 2_000_000_000_000_000_000u64.into(),
            ask: 2_000_000_000_000_000_000u64.into(),
            timestamp: chain_now,
        }])
        .call()
        .await
        .unwrap();

    let parent_before = fixture
        .user
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    keeper
        .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();
    assert!(
        fixture
            .deployment
            .pool
            .methods()
            .get_session(child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
            .is_none()
    );
    assert!(
        fixture
            .user
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap()
            > parent_before,
        "and the collateral comes home once a publisher returns"
    );
}