o2-tools 0.4.2-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
//! Credit: what the pool will lend, in what asset, and what it takes back.
//!
//! The loan cap, the inventory bound, the two "wrong door" errors, the in-kind
//! repayment walk, the settlement receipt, and the sell-side minimum the
//! keeper needs to plan an exit.

use super::*;
use crate::prop::{
    AssetBorrowed,
    AssetRepaid,
    PropOrderBookCleanup,
    QuoteReturned,
    SettlementReceived,
};

fn borrow_call(fixture: &PropFixture, asset: AssetId, amount: u64) -> CallContractArg {
    fixture.pool_call(
        fn_selector!(borrow(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(asset, amount)),
    )
}

fn repay_call(fixture: &PropFixture, asset: AssetId, amount: u64) -> CallContractArg {
    fixture.pool_call(fn_selector!(repay()), amount, asset, None)
}

/// Republishes the base price with a spread, so the two sides of the book can
/// be told apart in a valuation.
async fn publish_spread(fixture: &PropFixture, bid: u128, ask: u128) {
    fixture
        .deployment
        .price_feed
        .methods()
        .publish_prices(vec![PriceInput {
            asset: fixture.base_asset,
            bid,
            ask,
            timestamp: fixture.next_publish_time(),
        }])
        .call()
        .await
        .unwrap();
}

// ---------------------------------------------------------------------------
// The loan cap.
// ---------------------------------------------------------------------------

/// The cap counts an in-kind debt at the ASK - what buying the asset back
/// would cost - not at the bid the position would fetch. On a wide market
/// that is the difference between a line that is full and one that looks half
/// empty, and taking the cheaper side would let a session borrow twice what
/// the pool can be made whole for.
#[tokio::test]
async fn the_loan_cap_charges_an_in_kind_debt_at_the_ask() {
    let mut fixture = PropFixture::new().await;

    // A wide market: worth 1.0 to sell, costs 2.0 to buy back.
    publish_spread(
        &fixture,
        1_000_000_000_000_000_000,
        2_000_000_000_000_000_000,
    )
    .await;

    let line = fixture.session().await.credit_line;
    assert_eq!(line, 10_000_000);

    // 4e9 base units cost 8_000_000 at the ask - inside the line.
    fixture
        .call_account(
            vec![borrow_call(&fixture, fixture.base_asset, 4_000_000_000)],
            1,
        )
        .await
        .unwrap();
    assert_eq!(fixture.debt(fixture.base_asset).await, 4_000_000_000);

    // 2e9 more would be 4_000_000 at the BID - comfortably inside the line -
    // and 4_000_000 at the ask on top of the 8_000_000 already owed, which is
    // not. The ask is what decides it.
    let error = fixture
        .call_account(
            vec![borrow_call(&fixture, fixture.base_asset, 2_000_000_000)],
            1,
        )
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("LoanCapExceeded"),
        "the cap prices the buy-back, not the sale: {error:#}"
    );

    // Exactly to the line is allowed: 1e9 more is 2_000_000 at the ask.
    let response = fixture
        .call_account(
            vec![borrow_call(&fixture, fixture.base_asset, 1_000_000_000)],
            1,
        )
        .await
        .unwrap();
    let events = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<AssetBorrowed>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(events.len(), 1);
    assert_eq!(events[0].debt_total, 5_000_000_000);
    assert!(events[0].timestamp.unix != 0);

    // And one atomic unit past it is not: the charge rounds UP, so even a
    // fraction of a collateral unit is enough to refuse.
    let error = fixture
        .call_account(vec![borrow_call(&fixture, fixture.base_asset, 1)], 1)
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("LoanCapExceeded"),
        "the last unit is charged like every other: {error:#}"
    );

    // The draw shares the same cap, and the debt already counted against it
    // leaves no room at all.
    let error = fixture
        .call_account(vec![fixture.draw_call(1)], 1)
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("LoanCapExceeded"),
        "cash and in-kind exposure share one line: {error:#}"
    );
}

/// The pool cannot lend what it does not hold. Checked before the debt is
/// written, so a refused borrow leaves no trace on the ledger.
#[tokio::test]
async fn a_borrow_past_the_pools_float_is_refused_before_the_ledger_moves() {
    let mut fixture = PropFixture::new().await;

    let float = fixture.pool_balance(fixture.base_asset).await;
    assert!(float > 0);

    let error = fixture
        .call_account(
            vec![borrow_call(&fixture, fixture.base_asset, float + 1)],
            1,
        )
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("InsufficientInventory"),
        "the pool lends its float, not its ledger: {error:#}"
    );
    assert_eq!(fixture.debt(fixture.base_asset).await, 0);
    assert!(
        !fixture
            .deployment
            .pool
            .methods()
            .has_debts(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    );
    assert_eq!(fixture.pool_balance(fixture.base_asset).await, float);
}

// ---------------------------------------------------------------------------
// The two wrong doors, and the zero.
// ---------------------------------------------------------------------------

/// Quote and in-kind obligations live in different places - `drawn_quote` on
/// the session, the debt table for everything else - so each has its own call.
/// Handing the collateral asset to the in-kind door is refused with an error
/// that NAMES the right one rather than quietly doing nothing.
#[tokio::test]
async fn the_collateral_asset_is_routed_to_its_own_door_and_a_stranger_to_none() {
    let mut fixture = PropFixture::new().await;

    let error = fixture
        .call_account(
            vec![borrow_call(&fixture, fixture.collateral_asset, 1_000)],
            1,
        )
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("UseDraw"),
        "quote is drawn, not borrowed: {error:#}"
    );

    let error = fixture
        .call_account(
            vec![fixture.repay_base_from_collateral_call(fixture.collateral_asset, 1)],
            1,
        )
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("UseRepayQuote"),
        "a quote obligation nets without a price: {error:#}"
    );

    // An asset the tier never admitted has no book, no price pin and no place
    // in the valuation walk.
    let stranger = AssetId::new([0x81; 32]);
    let error = fixture
        .call_account(vec![borrow_call(&fixture, stranger, 1)], 1)
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("AssetNotInTier"),
        "the tier decides what may be borrowed: {error:#}"
    );
    let error = fixture
        .call_account(
            vec![fixture.pool_call(
                fn_selector!(withdraw(AssetId, u64)),
                0,
                AssetId::default(),
                Some(call_data!(stranger, 1u64)),
            )],
            2,
        )
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("AssetNotInTier"),
        "and what may be withdrawn: {error:#}"
    );

    // Zero is refused everywhere rather than logged as a no-op event.
    for (name, call) in [
        ("draw", fixture.draw_call(0)),
        ("borrow", borrow_call(&fixture, fixture.base_asset, 0)),
        (
            "withdraw",
            fixture.pool_call(
                fn_selector!(withdraw(AssetId, u64)),
                0,
                AssetId::default(),
                Some(call_data!(fixture.collateral_asset, 0u64)),
            ),
        ),
        (
            "repay_from_collateral",
            fixture.repay_from_collateral_call(0),
        ),
    ] {
        let error = fixture.call_account(vec![call], 2).await.unwrap_err();
        assert!(
            error.to_string().contains("AmountIsZero"),
            "{name} refuses a zero amount: {error:#}"
        );
    }
}

// ---------------------------------------------------------------------------
// Giving it back.
// ---------------------------------------------------------------------------

/// `return_quote` is forgiving where the rest of the pool is strict: an
/// overpayment is handed straight back rather than reverted, so a client that
/// races its own draw does not have to compute the outstanding balance to the
/// unit. The event still reports what was actually CREDITED.
#[tokio::test]
async fn returning_more_quote_than_was_drawn_hands_the_excess_straight_back() {
    let mut fixture = PropFixture::new().await;

    // The account needs more cash than it drew for the overpayment to exist.
    fixture
        .deployer
        .force_transfer_to_contract(
            fixture.child_id,
            500_000,
            fixture.collateral_asset,
            TxPolicies::default(),
        )
        .await
        .unwrap();
    fixture
        .call_account(vec![fixture.draw_call(1_000_000)], 1)
        .await
        .unwrap();
    assert_eq!(
        fixture.account_balance(fixture.collateral_asset).await,
        1_500_000
    );

    let response = fixture
        .call_account(
            vec![fixture.pool_call(
                fn_selector!(return_quote()),
                1_500_000,
                fixture.collateral_asset,
                None,
            )],
            1,
        )
        .await
        .unwrap();
    let events = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<QuoteReturned>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(events.len(), 1);
    assert_eq!(
        events[0].amount, 1_000_000,
        "the event reports what was credited, not what arrived"
    );
    assert_eq!(events[0].drawn_total, 0);
    assert_eq!(fixture.session().await.drawn_quote, 0);
    assert_eq!(
        fixture.account_balance(fixture.collateral_asset).await,
        500_000,
        "the excess went home to the account, not into the pool's float"
    );
}

/// In-kind repayment walks the debt down and, on the last unit, takes the
/// asset out of the debt INDEX - the enumerable set every exit gate reads.
/// A debt left in the index would block a close forever; one removed early
/// would let a session leave owing.
#[tokio::test]
async fn partial_repayments_walk_the_debt_down_and_clear_the_index_exactly_once() {
    let mut fixture = PropFixture::new().await;

    async fn has_debts(fixture: &PropFixture) -> bool {
        fixture
            .deployment
            .pool
            .methods()
            .has_debts(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    }

    fixture
        .call_account(
            vec![borrow_call(&fixture, fixture.base_asset, 1_000_000_000)],
            1,
        )
        .await
        .unwrap();
    assert!(has_debts(&fixture).await);

    // One unit more of the asset than the pool ever lent, so an over-repayment
    // is a rule the pool has to refuse rather than a balance it cannot fund.
    fixture
        .deployer
        .force_transfer_to_contract(
            fixture.child_id,
            1,
            fixture.base_asset,
            TxPolicies::default(),
        )
        .await
        .unwrap();

    fixture
        .call_account(
            vec![repay_call(&fixture, fixture.base_asset, 400_000_000)],
            0,
        )
        .await
        .unwrap();
    assert_eq!(fixture.debt(fixture.base_asset).await, 600_000_000);
    assert!(
        has_debts(&fixture).await,
        "a partly repaid debt still bars the exit gates"
    );

    // Repaying past the debt is refused rather than absorbed as a gift.
    let error = fixture
        .call_account(
            vec![repay_call(&fixture, fixture.base_asset, 600_000_001)],
            0,
        )
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("OverRepay"),
        "the pool takes back what it lent and no more: {error:#}"
    );

    let response = fixture
        .call_account(
            vec![repay_call(&fixture, fixture.base_asset, 600_000_000)],
            0,
        )
        .await
        .unwrap();
    let events = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<AssetRepaid>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(events.len(), 1);
    assert_eq!(events[0].debt_total, 0);
    assert_eq!(fixture.debt(fixture.base_asset).await, 0);
    assert!(
        !has_debts(&fixture).await,
        "the last unit takes the asset out of the index"
    );

    // With the debt gone the stray unit is the user's again, and repaying it
    // is refused for the same reason.
    let error = fixture
        .call_account(vec![repay_call(&fixture, fixture.base_asset, 1)], 0)
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("OverRepay"),
        "a cleared debt takes nothing more: {error:#}"
    );

    // And with the index empty the session closes cleanly.
    fixture.close_session().await;
    assert!(
        fixture
            .deployment
            .pool
            .methods()
            .get_session(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
            .is_none()
    );
}

// ---------------------------------------------------------------------------
// The settlement receipt.
// ---------------------------------------------------------------------------

/// `receive_settlement` is how the account hands a position to the pool during
/// a sweep, and it is reachable from a session key. That is safe because the
/// receipt is VALUE-NEUTRAL: the valuation counts `received` exactly as it
/// counts a balance on the account, so pushing funds across early moves the
/// session's health not one unit - and the receipt is scoped to the session
/// that sent it, so nothing leaks between sessions.
#[tokio::test]
async fn a_settlement_receipt_is_neutral_and_scoped_to_the_session_that_sent_it() {
    let mut fixture = PropFixture::new().await;

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

    fn push(fixture: &PropFixture, amount: u64, asset: AssetId) -> CallContractArg {
        fixture.pool_call(fn_selector!(receive_settlement()), amount, asset, None)
    }

    let call = push(&fixture, 400_000, fixture.collateral_asset);
    let response = fixture.call_account(vec![call], 0).await.unwrap();
    let events = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SettlementReceived>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(events.len(), 1);
    assert_eq!(events[0].received_total, 400_000);
    assert_eq!(events[0].session_id, 1);

    // Receipts accumulate rather than replace.
    let call = push(&fixture, 600_000, fixture.collateral_asset);
    let response = fixture.call_account(vec![call], 0).await.unwrap();
    let events = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SettlementReceived>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(events[0].received_total, 1_000_000);

    assert_eq!(
        fixture.session_value().await,
        before,
        "moving the cash across the pool's own boundary changes nothing"
    );
    assert_eq!(fixture.account_balance(fixture.collateral_asset).await, 0);

    // An asset outside the tier has no place in the settlement basket. The
    // account is given some first, so the refusal is the POOL's rule rather
    // than a balance the account could not forward.
    let stranger = AssetId::default();
    fixture
        .deployer
        .force_transfer_to_contract(fixture.child_id, 10, stranger, TxPolicies::default())
        .await
        .unwrap();
    let call = push(&fixture, 1, stranger);
    let error = fixture.call_account(vec![call], 0).await.unwrap_err();
    assert!(
        error.to_string().contains("AssetNotInTier"),
        "the basket holds tier assets only: {error:#}"
    );

    // And the draw still has to come back before the door opens, receipts or
    // not: the receipt is not a repayment.
    let error = fixture
        .account
        .methods()
        .close_session(Vec::<PropOrderBookCleanup>::new())
        .with_contracts(&[
            &fixture.deployment.pool,
            &fixture.deployment.oracle,
            &fixture.order_book.order_book,
            &fixture.deployment.price_feed,
        ])
        .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("QuoteOutstanding"),
        "a receipt is not a repayment: {error:#}"
    );
}

// ---------------------------------------------------------------------------
// What the keeper needs to plan an exit.
// ---------------------------------------------------------------------------

/// `min_sellable` answers the keeper's question - "what is the smallest
/// quantity of this asset a tier book will accept?" - and answers it three
/// ways: a number when a bid exists, `None` when no tier book trades the
/// asset at all, and a REVERT when a book exists but has no bid, because a
/// silent `None` there would read as "nothing to do".
#[tokio::test]
async fn min_sellable_separates_no_market_from_no_bid() {
    let fixture = PropFixture::new().await;

    // The collateral asset is a QUOTE everywhere in the tier, never a base, so
    // no book can take it.
    assert_eq!(
        fixture
            .deployment
            .pool
            .methods()
            .min_sellable(fixture.child_id, fixture.collateral_asset)
            .with_contract_ids(&[fixture.order_book.contract_id])
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        None,
        "an asset no tier book trades has no minimum"
    );

    // The base asset has a book, but the book is empty.
    let error = fixture
        .deployment
        .pool
        .methods()
        .min_sellable(fixture.child_id, fixture.base_asset)
        .with_contract_ids(&[fixture.order_book.contract_id])
        .simulate(Execution::state_read_only())
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("NoBestBid"),
        "an empty book is a liveness problem, not an absence: {error:#}"
    );

    // With a bid resting, the minimum is the smallest base quantity whose
    // value at that bid reaches the book's own quote minimum, rounded UP.
    fixture
        .rest_order(
            1_900_000,
            1_000_000_000,
            fixture.collateral_asset,
            1_900_000,
        )
        .await;
    assert_eq!(
        fixture
            .deployment
            .pool
            .methods()
            .min_sellable(fixture.child_id, fixture.base_asset)
            .with_contract_ids(&[fixture.order_book.contract_id])
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        Some(527),
        "ceil(MIN_ORDER * BASE_DECIMALS / best_bid) = ceil(1e9 / 1_900_000)"
    );
}