o2-tools 0.4.7-rc2

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
//! Daily loss policy is published onchain and enforced by the backend.
//! It never changes the pool's health checks or settlement eligibility.

use super::*;
use crate::prop::TierDailyLossLimitPublished;

async fn daily_loss_limit(
    fixture: &PropFixture,
    tier_id: u64,
    version: u32,
) -> Option<u64> {
    fixture
        .deployment
        .pool
        .methods()
        .get_daily_loss_limit(tier_id, version)
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value
}

async fn publish_daily_loss_tier(
    fixture: &PropFixture,
    limit: Option<u64>,
) -> CallResponse<u32> {
    fixture
        .deployment
        .pool
        .methods()
        .publish_tier_v3(
            TURBO_TIER_ID,
            turbo_tier_params(),
            turbo_terms(DRAWDOWN_SCHEDULE),
            vec![fixture.order_book.contract_id],
            limit,
        )
        .with_contract_ids(&[
            fixture.order_book.contract_id,
            fixture.deployment.price_feed_id,
        ])
        .call()
        .await
        .unwrap()
}

#[tokio::test]
async fn v3_publishes_daily_policy_atomically_without_changing_the_tier_event() {
    let fixture = PropFixture::new().await;
    let pool = &fixture.deployment.pool;
    assert_eq!(daily_loss_limit(&fixture, TIER_ID, 1).await, None);
    assert_eq!(daily_loss_limit(&fixture, TURBO_TIER_ID, 1).await, None);

    for (index, limit) in [Some(100), None, Some(0), Some(10_000)]
        .into_iter()
        .enumerate()
    {
        let response = publish_daily_loss_tier(&fixture, limit).await;
        let version = index as u32 + 1;
        assert_eq!(response.value, version);
        assert_eq!(
            daily_loss_limit(&fixture, TURBO_TIER_ID, version).await,
            limit
        );
        let published = response
            .decode_logs_with_type::<TierVersionPublishedV2>()
            .unwrap();
        assert_eq!(published.len(), 1);
        assert_eq!(published[0].tier_id, TURBO_TIER_ID);
        assert_eq!(published[0].version, version);
        assert_eq!(published[0].params, turbo_tier_params());
        assert_eq!(published[0].terms, turbo_terms(DRAWDOWN_SCHEDULE));
        assert_eq!(published[0].books, vec![fixture.order_book.contract_id]);
        assert_eq!(
            published[0].assets,
            vec![fixture.base_asset, fixture.collateral_asset]
        );
        assert_eq!(published[0].k, LINE);
        assert_eq!(published[0].required_collateral, TURBO_DEPOSIT);
        assert_eq!(published[0].term_seconds, turbo_tier_params().duration);
        assert!(published[0].timestamp.unix > 0);
        assert!(
            response
                .decode_logs_with_type::<TierVersionPublished>()
                .unwrap()
                .is_empty()
        );

        let policies = response
            .decode_logs_with_type::<TierDailyLossLimitPublished>()
            .unwrap();
        assert_eq!(policies.len(), 1);
        assert_eq!(policies[0].tier_id, TURBO_TIER_ID);
        assert_eq!(policies[0].version, version);
        assert_eq!(policies[0].daily_loss_limit_bps, limit);
        assert_eq!(policies[0].timestamp, published[0].timestamp);
        assert_eq!(
            pool.methods()
                .get_tier(TURBO_TIER_ID, version)
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            Some(turbo_tier_params())
        );
        assert_eq!(
            pool.methods()
                .get_turbo_terms(TURBO_TIER_ID, version)
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            Some(turbo_terms(DRAWDOWN_SCHEDULE))
        );
    }

    // A later V2 publication does not inherit the previous version's policy.
    let v2 = publish_turbo_tier_unarmed(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    assert_eq!(v2, 5);
    assert_eq!(daily_loss_limit(&fixture, TURBO_TIER_ID, v2).await, None);
    assert_eq!(
        daily_loss_limit(&fixture, TURBO_TIER_ID, 1).await,
        Some(100)
    );
    assert_eq!(daily_loss_limit(&fixture, TURBO_TIER_ID, 2).await, None);
    assert_eq!(daily_loss_limit(&fixture, TURBO_TIER_ID, 3).await, Some(0));
    assert_eq!(
        daily_loss_limit(&fixture, TURBO_TIER_ID, 4).await,
        Some(10_000)
    );
    assert_eq!(daily_loss_limit(&fixture, TIER_ID, 1).await, None);
}

#[tokio::test]
async fn daily_policy_updates_are_scoped_to_a_version_and_visible_to_live_sessions() {
    let fixture = PropFixture::new().await;
    let pool = &fixture.deployment.pool;
    let version = publish_daily_loss_tier(&fixture, Some(100)).await.value;
    open_turbo_session(&fixture).await;
    let session = fixture.session().await;
    let lines = fixture.lines().await;
    let newer = publish_daily_loss_tier(&fixture, Some(200)).await.value;

    // Governance can repair backend policy while paused, including on a
    // historical tier version, without republishing or changing a session.
    pool.methods().pause().call().await.unwrap();
    for limit in [Some(50), Some(0), None, None, Some(1), Some(10_000)] {
        let response = pool
            .methods()
            .set_daily_loss_limit(TURBO_TIER_ID, version, limit)
            .call()
            .await
            .unwrap();
        let events = response
            .decode_logs_with_type::<TierDailyLossLimitPublished>()
            .unwrap();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].tier_id, TURBO_TIER_ID);
        assert_eq!(events[0].version, version);
        assert_eq!(events[0].daily_loss_limit_bps, limit);
        let now = fixture
            .deployer
            .try_provider()
            .unwrap()
            .latest_block_time()
            .await
            .unwrap()
            .unwrap()
            .timestamp() as u64;
        assert_eq!(events[0].timestamp.unix, now);
        assert!(
            response
                .decode_logs_with_type::<TierVersionPublishedV2>()
                .unwrap()
                .is_empty()
        );
        assert_eq!(
            daily_loss_limit(&fixture, session.tier_id, session.tier_version).await,
            limit
        );
        assert_eq!(
            daily_loss_limit(&fixture, TURBO_TIER_ID, newer).await,
            Some(200)
        );
        assert_eq!(fixture.session().await, session);
    }
    pool.methods()
        .set_daily_loss_limit(TIER_ID, 1, Some(25))
        .call()
        .await
        .unwrap();
    assert_eq!(daily_loss_limit(&fixture, TIER_ID, 1).await, Some(25));
    assert_eq!(
        daily_loss_limit(&fixture, TURBO_TIER_ID, version).await,
        Some(10_000)
    );
    assert_eq!(
        pool.methods()
            .current_tier_version(TURBO_TIER_ID)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        Some(newer)
    );
    pool.methods().unpause().call().await.unwrap();
    assert_eq!(fixture.lines().await, lines);
    assert_eq!(
        pool.methods()
            .get_turbo_terms(TURBO_TIER_ID, version)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        Some(turbo_terms(DRAWDOWN_SCHEDULE))
    );
}

#[tokio::test]
async fn daily_policy_requires_an_admin_and_an_existing_tier_version() {
    let fixture = PropFixture::new().await;
    let pool = &fixture.deployment.pool;
    let version = publish_daily_loss_tier(&fixture, Some(100)).await.value;
    let outsider = Identity::Address(fixture.outsider.address());
    pool.methods()
        .grant_role(ACCOUNT_CLOSER_ROLE, outsider)
        .call()
        .await
        .unwrap();
    pool.methods()
        .grant_role(DISCOUNT_MANAGER_ROLE, outsider)
        .call()
        .await
        .unwrap();
    pool.methods()
        .set_liquidator(outsider)
        .call()
        .await
        .unwrap();

    for caller in [&fixture.user, &fixture.outsider] {
        let unauthorized = pool.clone().with_account(caller.clone());
        let error = unauthorized
            .methods()
            .set_daily_loss_limit(TURBO_TIER_ID, version, None)
            .call()
            .await
            .unwrap_err();
        assert!(
            error.to_string().contains("AccessControlNotAuthorized"),
            "{error:#}"
        );
        let error = unauthorized
            .methods()
            .publish_tier_v3(
                TURBO_TIER_ID,
                turbo_tier_params(),
                turbo_terms(DRAWDOWN_SCHEDULE),
                vec![fixture.order_book.contract_id],
                Some(0),
            )
            .with_contract_ids(&[
                fixture.order_book.contract_id,
                fixture.deployment.price_feed_id,
            ])
            .call()
            .await
            .unwrap_err();
        assert!(
            error.to_string().contains("AccessControlNotAuthorized"),
            "{error:#}"
        );
    }
    for (tier_id, absent_version) in
        [(TURBO_TIER_ID, 0), (TURBO_TIER_ID, version + 1), (999, 1)]
    {
        let error = pool
            .methods()
            .set_daily_loss_limit(tier_id, absent_version, Some(50))
            .call()
            .await
            .unwrap_err();
        assert!(
            error.to_string().contains("InvalidTierVersion"),
            "{error:#}"
        );
        assert_eq!(
            daily_loss_limit(&fixture, tier_id, absent_version).await,
            None
        );
    }
    assert_eq!(
        daily_loss_limit(&fixture, TURBO_TIER_ID, version).await,
        Some(100)
    );
    assert_eq!(
        pool.methods()
            .current_tier_version(TURBO_TIER_ID)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        Some(version)
    );

    // The access-control grant, rather than the deployer's identity, owns policy.
    pool.methods().grant_role(0, outsider).call().await.unwrap();
    let delegated = pool.clone().with_account(fixture.outsider.clone());
    delegated
        .methods()
        .set_daily_loss_limit(TURBO_TIER_ID, version, Some(80))
        .call()
        .await
        .unwrap();
    pool.methods()
        .revoke_role(0, outsider)
        .call()
        .await
        .unwrap();
    let error = delegated
        .methods()
        .set_daily_loss_limit(TURBO_TIER_ID, version, None)
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("AccessControlNotAuthorized"),
        "{error:#}"
    );
    assert_eq!(
        daily_loss_limit(&fixture, TURBO_TIER_ID, version).await,
        Some(80)
    );
}

#[tokio::test]
async fn invalid_daily_basis_points_cannot_replace_policy_or_publish_a_version() {
    let fixture = PropFixture::new().await;
    let pool = &fixture.deployment.pool;
    let version = publish_daily_loss_tier(&fixture, Some(0)).await.value;
    for invalid in [10_001, u64::MAX] {
        let error = pool
            .methods()
            .set_daily_loss_limit(TURBO_TIER_ID, version, Some(invalid))
            .call()
            .await
            .unwrap_err();
        assert!(
            error.to_string().contains("InvalidDailyLossLimit"),
            "{error:#}"
        );
        let error = pool
            .methods()
            .publish_tier_v3(
                TURBO_TIER_ID,
                turbo_tier_params(),
                turbo_terms(DRAWDOWN_SCHEDULE),
                vec![fixture.order_book.contract_id],
                Some(invalid),
            )
            .with_contract_ids(&[
                fixture.order_book.contract_id,
                fixture.deployment.price_feed_id,
            ])
            .call()
            .await
            .unwrap_err();
        assert!(
            error.to_string().contains("InvalidDailyLossLimit"),
            "{error:#}"
        );
        assert_eq!(
            daily_loss_limit(&fixture, TURBO_TIER_ID, version).await,
            Some(0)
        );
        assert_eq!(
            daily_loss_limit(&fixture, TURBO_TIER_ID, version + 1).await,
            None
        );
        assert_eq!(
            pool.methods()
                .get_tier(TURBO_TIER_ID, version + 1)
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            None
        );
        assert_eq!(
            pool.methods()
                .get_turbo_terms(TURBO_TIER_ID, version + 1)
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            None
        );
        assert_eq!(
            pool.methods()
                .current_tier_version(TURBO_TIER_ID)
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            Some(version)
        );
    }
    assert_eq!(
        publish_daily_loss_tier(&fixture, None).await.value,
        version + 1
    );
}

#[tokio::test]
async fn refused_v3_publications_leave_no_policy_or_partial_tier() {
    let fixture = PropFixture::new().await;
    let pool = &fixture.deployment.pool;
    let version = publish_daily_loss_tier(&fixture, Some(100)).await.value;
    let mut invalid_terms = turbo_terms(DRAWDOWN_SCHEDULE);
    invalid_terms.max_loss_bps = [0; 4];
    let mut invalid_params = turbo_tier_params();
    invalid_params.liq_price_factor = 0;
    for (params, terms, books, expected) in [
        (
            turbo_tier_params(),
            invalid_terms,
            vec![fixture.order_book.contract_id],
            "InvalidTurboTerms",
        ),
        (
            invalid_params,
            turbo_terms(DRAWDOWN_SCHEDULE),
            vec![fixture.order_book.contract_id],
            "InvalidTierParams",
        ),
        // Duplicate admission fails after the version and first book were written.
        (
            turbo_tier_params(),
            turbo_terms(DRAWDOWN_SCHEDULE),
            vec![fixture.order_book.contract_id; 2],
            "InvalidBook",
        ),
    ] {
        let error = pool
            .methods()
            .publish_tier_v3(TURBO_TIER_ID, params, terms, books, Some(1))
            .with_contract_ids(&[
                fixture.order_book.contract_id,
                fixture.deployment.price_feed_id,
            ])
            .call()
            .await
            .unwrap_err();
        assert!(error.to_string().contains(expected), "{error:#}");
        assert_eq!(
            pool.methods()
                .current_tier_version(TURBO_TIER_ID)
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            Some(version)
        );
        assert_eq!(
            pool.methods()
                .get_tier(TURBO_TIER_ID, version + 1)
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            None
        );
        assert_eq!(
            pool.methods()
                .get_turbo_terms(TURBO_TIER_ID, version + 1)
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            None
        );
        assert_eq!(
            daily_loss_limit(&fixture, TURBO_TIER_ID, version + 1).await,
            None
        );
        assert_eq!(
            daily_loss_limit(&fixture, TURBO_TIER_ID, version).await,
            Some(100)
        );
    }
    assert_eq!(
        publish_daily_loss_tier(&fixture, Some(200)).await.value,
        version + 1
    );
}

#[tokio::test]
async fn permissioned_closure_needs_no_daily_policy_or_daily_loss_breach() {
    for limit in [None, Some(0), Some(10_000)] {
        let fixture = PropFixture::new().await;
        let version = publish_daily_loss_tier(&fixture, limit).await.value;
        let opened = open_turbo_session(&fixture).await;
        fixture
            .deployment
            .pool
            .methods()
            .grant_role(
                ACCOUNT_CLOSER_ROLE,
                Identity::Address(fixture.outsider.address()),
            )
            .call()
            .await
            .unwrap();
        assert!(!fixture.is_liquidatable().await);
        let response = fixture
            .force_close_session(&fixture.outsider, vec![])
            .await
            .unwrap();
        let closed = fixture.closed_event(&response);
        assert_eq!(closed.session_id, opened.session_id);
        assert_eq!(closed.reason, SettlementReason::PermissionedClosure);
        assert_eq!(closed.bad_debt, 0);
        assert_eq!(closed.user_net, 0);
        let seized = response.decode_logs_with_type::<SessionSeized>().unwrap();
        assert_eq!(seized.len(), 1);
        assert_eq!(seized[0].reason, SettlementReason::PermissionedClosure);
        assert!(fixture.session_opt().await.is_none());
        assert_eq!(
            daily_loss_limit(&fixture, TURBO_TIER_ID, version).await,
            limit
        );
    }
}

async fn buy_one_base(fixture: &mut PropFixture) {
    let quantity = 1_000_000_000;
    let cost = 2_000_000;
    fixture
        .rest_order(2_000_000, quantity, fixture.base_asset, quantity)
        .await;
    let draw = fixture.draw_call(cost);
    let buy = fixture.book_call(2_000_000, quantity, fixture.collateral_asset, cost);
    fixture
        .call_account(vec![draw, buy, fixture.settle_book_call()], 2)
        .await
        .unwrap();
}

#[tokio::test]
async fn a_daily_loss_breach_does_not_change_health_or_grant_closure_rights() {
    let mut fixture = PropFixture::new().await;
    let version = publish_daily_loss_tier(&fixture, Some(10)).await.value;
    open_turbo_session(&fixture).await;
    buy_one_base(&mut fixture).await;
    // A 50,000 loss breaches a 10 bps limit (10,000 of this line), but remains within
    // the tier's 150,000 total drawdown, including the absorption haircut.
    fixture.publish_base_price(1_950_000_000_000_000_000).await;
    assert!(!fixture.is_liquidatable().await);
    let lines = fixture.lines().await;
    let pool = &fixture.deployment.pool;
    let error = pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .liquidate(fixture.child_id, vec![])
        .with_contracts(&[
            &fixture.account,
            &fixture.deployment.oracle,
            &fixture.order_book.order_book,
            &fixture.deployment.price_feed,
        ])
        .call()
        .await
        .unwrap_err();
    assert!(error.to_string().contains("NotLiquidatable"), "{error:#}");
    let error = fixture
        .force_close_session(&fixture.outsider, vec![])
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("AccessControlNotAuthorized"),
        "{error:#}"
    );

    for limit in [None, Some(0), Some(10_000)] {
        pool.methods()
            .set_daily_loss_limit(TURBO_TIER_ID, version, limit)
            .call()
            .await
            .unwrap();
        assert_eq!(fixture.lines().await, lines);
    }
    // The backend may close after a policy update; the pool does not recheck
    // whether the loss still exceeds the latest configured daily limit.
    pool.methods()
        .grant_role(
            ACCOUNT_CLOSER_ROLE,
            Identity::Address(fixture.outsider.address()),
        )
        .call()
        .await
        .unwrap();
    let response = fixture
        .force_close_session(&fixture.outsider, vec![])
        .await
        .unwrap();
    let closed = fixture.closed_event(&response);
    assert_eq!(closed.reason, SettlementReason::PermissionedClosure);
    assert!(closed.profit_is_negative);
    assert_eq!(closed.profit_abs, 69_500);
    assert_eq!(closed.bad_debt, 0);
    assert!(fixture.session_opt().await.is_none());
}

#[tokio::test]
async fn daily_policy_leaves_voluntary_closure_and_onchain_liquidation_available() {
    for liquidate in [false, true] {
        let mut fixture = PropFixture::new().await;
        let limit = if liquidate { 10_000 } else { 1 };
        publish_daily_loss_tier(&fixture, Some(limit)).await;
        open_turbo_session(&fixture).await;
        if liquidate {
            buy_one_base(&mut fixture).await;
            fixture.publish_base_price(1_800_000_000_000_000_000).await;
        }
        assert_eq!(fixture.is_liquidatable().await, liquidate);
        let response = if liquidate {
            fixture.liquidate().await
        } else {
            fixture.close_session().await
        };
        assert_eq!(
            fixture.closed_event(&response).reason,
            if liquidate {
                SettlementReason::Liquidation
            } else {
                SettlementReason::UserClose
            }
        );
        assert!(fixture.session_opt().await.is_none());
    }
}