forked from Agoric/agoric-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest-vaultLiquidation.js
3424 lines (2976 loc) · 106 KB
/
test-vaultLiquidation.js
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
import '@agoric/zoe/exported.js';
import { test as unknownTest } from '@agoric/zoe/tools/prepare-test-env-ava.js';
import { AmountMath, makeIssuerKit } from '@agoric/ertp';
import { allValues, makeTracer, objectMap } from '@agoric/internal';
import { unsafeMakeBundleCache } from '@agoric/swingset-vat/tools/bundleTool.js';
import {
ceilMultiplyBy,
makeRatio,
makeRatioFromAmounts,
} from '@agoric/zoe/src/contractSupport/index.js';
import { eventLoopIteration } from '@agoric/internal/src/testing-utils.js';
import { buildManualTimer } from '@agoric/swingset-vat/tools/manual-timer.js';
import { E } from '@endo/eventual-send';
import { deeplyFulfilled } from '@endo/marshal';
import { TimeMath } from '@agoric/time';
import { assertPayoutAmount } from '@agoric/zoe/test/zoeTestHelpers.js';
import { multiplyBy } from '@agoric/zoe/src/contractSupport/ratio.js';
import { NonNullish } from '@agoric/assert';
import {
SECONDS_PER_DAY as ONE_DAY,
SECONDS_PER_HOUR as ONE_HOUR,
SECONDS_PER_MINUTE as ONE_MINUTE,
SECONDS_PER_WEEK as ONE_WEEK,
startVaultFactory,
} from '../../src/proposals/econ-behaviors.js';
import '../../src/vaultFactory/types.js';
import {
reserveInitialState,
subscriptionTracker,
vaultManagerMetricsTracker,
} from '../metrics.js';
import { setUpZoeForTest, withAmountUtils } from '../supports.js';
import {
BASIS_POINTS,
defaultParamValues,
getRunFromFaucet,
legacyOfferResult,
setupElectorateReserveAndAuction,
} from './vaultFactoryUtils.js';
/**
* @typedef {Record<string, any> & {
* aeth: IssuerKit & import('../supports.js').AmountUtils;
* run: IssuerKit & import('../supports.js').AmountUtils;
* bundleCache: Awaited<ReturnType<typeof unsafeMakeBundleCache>>;
* rates: VaultManagerParamValues;
* interestTiming: InterestTiming;
* zoe: ZoeService;
* }} Context
*/
/** @type {import('ava').TestFn<Context>} */
const test = unknownTest;
const contractRoots = {
faucet: './test/vaultFactory/faucet.js',
VaultFactory: './src/vaultFactory/vaultFactory.js',
reserve: './src/reserve/assetReserve.js',
auctioneer: './src/auction/auctioneer.js',
};
/** @typedef {import('../../src/vaultFactory/vaultFactory.js').VaultFactoryContract} VFC */
const trace = makeTracer('TestST', false);
// Define locally to test that vaultFactory uses these values
export const Phase = /** @type {const} */ ({
ACTIVE: 'active',
LIQUIDATING: 'liquidating',
CLOSED: 'closed',
LIQUIDATED: 'liquidated',
TRANSFER: 'transfer',
});
test.before(async t => {
const { zoe, feeMintAccessP } = await setUpZoeForTest();
const stableIssuer = await E(zoe).getFeeIssuer();
const stableBrand = await E(stableIssuer).getBrand();
// @ts-expect-error missing mint
const run = withAmountUtils({ issuer: stableIssuer, brand: stableBrand });
const aeth = withAmountUtils(
makeIssuerKit('aEth', 'nat', { decimalPlaces: 6 }),
);
const bundleCache = await unsafeMakeBundleCache('./bundles/'); // package-relative
// note that the liquidation might be a different bundle name
const bundles = await allValues({
faucet: bundleCache.load(contractRoots.faucet, 'faucet'),
VaultFactory: bundleCache.load(contractRoots.VaultFactory, 'VaultFactory'),
reserve: bundleCache.load(contractRoots.reserve, 'reserve'),
auctioneer: bundleCache.load(contractRoots.auctioneer, 'auction'),
});
const installation = objectMap(bundles, bundle => E(zoe).install(bundle));
const feeMintAccess = await feeMintAccessP;
const contextPs = {
zoe,
feeMintAccess,
bundles,
installation,
electorateTerms: undefined,
interestTiming: {
chargingPeriod: 2n,
recordingPeriod: 6n,
},
minInitialDebt: 50n,
referencedUi: undefined,
rates: defaultParamValues(run.brand),
};
const frozenCtx = await deeplyFulfilled(harden(contextPs));
t.context = {
...frozenCtx,
bundleCache,
aeth,
run,
};
trace(t, 'CONTEXT');
});
/**
* NOTE: called separately by each test so zoe/priceAuthority don't interfere
*
* @param {import('ava').ExecutionContext<Context>} t
* @param {NatValue[] | Ratio} priceOrList
* @param {Amount | undefined} unitAmountIn
* @param {import('@agoric/time').TimerService} timer
* @param {RelativeTime} quoteInterval
* @param {bigint} stableInitialLiquidity
* @param {Partial<import('../../src/auction/params.js').AuctionParams>} [auctionParams]
*/
const setupServices = async (
t,
priceOrList,
unitAmountIn,
timer = buildManualTimer(),
quoteInterval = 1n,
stableInitialLiquidity,
auctionParams = {},
) => {
const {
zoe,
run,
aeth,
interestTiming,
minInitialDebt,
referencedUi,
rates,
} = t.context;
t.context.timer = timer;
const { space, priceAuthorityAdmin, aethTestPriceAuthority } =
await setupElectorateReserveAndAuction(
t,
// @ts-expect-error inconsistent types with withAmountUtils
run,
aeth,
priceOrList,
quoteInterval,
unitAmountIn,
auctionParams,
);
const { consume } = space;
const {
installation: { produce: iProduce },
} = space;
iProduce.VaultFactory.resolve(t.context.installation.VaultFactory);
iProduce.liquidate.resolve(t.context.installation.liquidate);
await startVaultFactory(
space,
{ interestTiming, options: { referencedUi } },
minInitialDebt,
);
const governorCreatorFacet = E.get(
consume.vaultFactoryKit,
).governorCreatorFacet;
/** @type {Promise<VaultFactoryCreatorFacet>} */
const vaultFactoryCreatorFacetP = E.get(consume.vaultFactoryKit).creatorFacet;
const reserveCreatorFacet = E.get(consume.reserveKit).creatorFacet;
const reservePublicFacet = E.get(consume.reserveKit).publicFacet;
// XXX just pass through reserveKit from the space
const reserveKit = { reserveCreatorFacet, reservePublicFacet };
// Add a vault that will lend on aeth collateral
/** @type {Promise<VaultManager>} */
const aethVaultManagerP = E(vaultFactoryCreatorFacetP).addVaultType(
aeth.issuer,
'AEth',
rates,
);
/** @typedef {import('../../src/proposals/econ-behaviors.js').AuctioneerKit} AuctioneerKit */
/** @typedef {import('@agoric/zoe/tools/manualPriceAuthority.js').ManualPriceAuthority} ManualPriceAuthority */
/**
* @type {[
* any,
* VaultFactoryCreatorFacet,
* VFC['publicFacet'],
* VaultManager,
* AuctioneerKit,
* ManualPriceAuthority,
* CollateralManager,
* ]}
*/
const [
governorInstance,
vaultFactory, // creator
vfPublic,
aethVaultManager,
auctioneerKit,
priceAuthority,
aethCollateralManager,
] = await Promise.all([
E(consume.agoricNames).lookup('instance', 'VaultFactoryGovernor'),
vaultFactoryCreatorFacetP,
E.get(consume.vaultFactoryKit).publicFacet,
aethVaultManagerP,
consume.auctioneerKit,
/** @type {Promise<ManualPriceAuthority>} */ (consume.priceAuthority),
E(aethVaultManagerP).getPublicFacet(),
]);
trace(t, 'pa', {
governorInstance,
vaultFactory,
vfPublic,
priceAuthority: !!priceAuthority,
});
const { g, v } = {
g: {
governorInstance,
governorPublicFacet: E(zoe).getPublicFacet(governorInstance),
governorCreatorFacet,
},
v: {
vaultFactory,
vfPublic,
aethVaultManager,
aethCollateralManager,
},
};
await E(auctioneerKit.creatorFacet).addBrand(aeth.issuer, 'Aeth');
return {
zoe,
timer,
governor: g,
vaultFactory: v,
runKit: { issuer: run.issuer, brand: run.brand },
priceAuthority,
reserveKit,
auctioneerKit,
priceAuthorityAdmin,
aethTestPriceAuthority,
};
};
const setClockAndAdvanceNTimes = async (timer, times, start, incr = 1n) => {
let currentTime = start;
// first time through is at START, then n TIMES more plus INCR
for (let i = 0; i <= times; i += 1) {
trace('advancing clock to ', currentTime);
await timer.advanceTo(TimeMath.absValue(currentTime));
await eventLoopIteration();
currentTime = TimeMath.addAbsRel(currentTime, TimeMath.relValue(incr));
}
return currentTime;
};
const bid = async (t, zoe, auctioneerKit, aeth, bidAmount, desired) => {
const bidderSeat = await E(zoe).offer(
E(auctioneerKit.publicFacet).makeBidInvitation(aeth.brand),
harden({ give: { Bid: bidAmount } }),
harden({ Bid: getRunFromFaucet(t, bidAmount.value) }),
{ maxBuy: desired, offerPrice: makeRatioFromAmounts(bidAmount, desired) },
);
return bidderSeat;
};
const bidPrice = async (
t,
zoe,
auctioneerKit,
aeth,
bidAmount,
desired,
offerPrice,
) => {
const bidderSeat = await E(zoe).offer(
E(auctioneerKit.publicFacet).makeBidInvitation(aeth.brand),
harden({ give: { Bid: bidAmount } }),
harden({ Bid: getRunFromFaucet(t, bidAmount.value) }),
{ maxBuy: desired, offerPrice },
);
return bidderSeat;
};
const bidDiscount = async (
t,
zoe,
auctioneerKit,
aeth,
bidAmount,
desired,
scale,
) => {
const bidderSeat = await E(zoe).offer(
E(auctioneerKit.publicFacet).makeBidInvitation(aeth.brand),
harden({ give: { Bid: bidAmount } }),
harden({ Bid: getRunFromFaucet(t, bidAmount.value) }),
{ maxBuy: desired, offerBidScaling: scale },
);
return bidderSeat;
};
// Calculate the nominalStart time (when liquidations happen), and the priceLock
// time (when prices are locked). Advance the clock to the priceLock time, then
// to the nominal start time. return the nominal start time and the auction
// start time, so the caller can check on liquidations in process before
// advancing the clock.
const startAuctionClock = async (auctioneerKit, manualTimer) => {
const schedule = await E(auctioneerKit.creatorFacet).getSchedule();
const priceDelay = await E(auctioneerKit.publicFacet).getPriceLockPeriod();
const { startTime, startDelay } = schedule.nextAuctionSchedule;
const nominalStart = TimeMath.subtractAbsRel(startTime, startDelay);
const priceLockTime = TimeMath.subtractAbsRel(nominalStart, priceDelay);
await manualTimer.advanceTo(TimeMath.absValue(priceLockTime));
await eventLoopIteration();
await manualTimer.advanceTo(TimeMath.absValue(nominalStart));
await eventLoopIteration();
return { startTime, time: nominalStart };
};
const assertBidderPayout = async (t, bidderSeat, run, curr, aeth, coll) => {
const bidderResult = await E(bidderSeat).getOfferResult();
t.is(bidderResult, 'Your bid has been accepted');
const payouts = await E(bidderSeat).getPayouts();
const { Collateral: bidderCollateral, Bid: bidderBid } = payouts;
(!bidderBid && curr === 0n) ||
(await assertPayoutAmount(t, run.issuer, bidderBid, run.make(curr)));
(!bidderCollateral && coll === 0n) ||
(await assertPayoutAmount(
t,
aeth.issuer,
bidderCollateral,
aeth.make(coll),
'amount ',
));
};
test('price drop', async t => {
const { zoe, aeth, run, rates } = t.context;
const manualTimer = buildManualTimer();
// The price starts at 5 RUN per Aeth. The loan will start with 400 Aeth
// collateral and a loan of 1600, which is a CR of 1.25. After the price falls
// to 4, the loan will get liquidated.
t.context.interestTiming = {
chargingPeriod: 2n,
recordingPeriod: 10n,
};
const services = await setupServices(
t,
makeRatio(50n, run.brand, 10n, aeth.brand),
aeth.make(400n),
manualTimer,
undefined,
500n,
{ StartFrequency: ONE_HOUR },
);
const {
vaultFactory: { vaultFactory, aethCollateralManager },
aethTestPriceAuthority,
reserveKit: { reserveCreatorFacet, reservePublicFacet },
auctioneerKit,
} = services;
const metricsTopic = await E.get(E(reservePublicFacet).getPublicTopics())
.metrics;
const m = await subscriptionTracker(t, metricsTopic);
await m.assertInitial(reserveInitialState(run.makeEmpty()));
await E(reserveCreatorFacet).addIssuer(aeth.issuer, 'Aeth');
const collateralAmount = aeth.make(400n);
const wantMinted = run.make(1600n);
/** @type {UserSeat<VaultKit>} */
const vaultSeat = await E(zoe).offer(
await E(aethCollateralManager).makeVaultInvitation(),
harden({
give: { Collateral: collateralAmount },
want: { Minted: wantMinted },
}),
harden({
Collateral: aeth.mint.mintPayment(collateralAmount),
}),
);
trace(t, 'vault made', wantMinted);
// A bidder places a bid //////////////////////////
const bidAmount = run.make(2000n);
const desired = aeth.make(400n);
const bidderSeat = await bid(t, zoe, auctioneerKit, aeth, bidAmount, desired);
const {
vault,
publicNotifiers: { vault: vaultNotifier },
} = await legacyOfferResult(vaultSeat);
trace(t, 'offer result', vault);
const debtAmount = await E(vault).getCurrentDebt();
const fee = ceilMultiplyBy(wantMinted, rates.mintFee);
t.deepEqual(
debtAmount,
AmountMath.add(wantMinted, fee),
'borrower Minted amount does not match',
);
let notification = await E(vaultNotifier).getUpdateSince();
trace(t, 'got notification', notification);
t.is(notification.value.vaultState, Phase.ACTIVE);
t.deepEqual((await notification.value).debtSnapshot, {
debt: AmountMath.add(wantMinted, fee),
interest: makeRatio(100n, run.brand),
});
const { Minted: lentAmount } = await E(vaultSeat).getFinalAllocation();
t.truthy(AmountMath.isEqual(lentAmount, wantMinted), 'received 470 Minted');
t.deepEqual(
await E(vault).getCollateralAmount(),
aeth.make(400n),
'vault holds 11 Collateral',
);
trace(t, 'pa2', { aethPriceAuthority: aethTestPriceAuthority });
await aethTestPriceAuthority.setPrice(
makeRatio(40n, run.brand, 10n, aeth.brand),
);
trace(t, 'price dropped a little');
notification = await E(vaultNotifier).getUpdateSince();
t.is(notification.value.vaultState, Phase.ACTIVE);
const { startTime, time } = await startAuctionClock(
auctioneerKit,
manualTimer,
);
let currentTime = time;
notification = await E(vaultNotifier).getUpdateSince();
t.is(notification.value.vaultState, Phase.LIQUIDATING);
t.deepEqual(
await E(vault).getCollateralAmount(),
aeth.makeEmpty(),
'Collateral consumed while liquidating',
);
t.deepEqual(
await E(vault).getCurrentDebt(),
AmountMath.add(wantMinted, run.make(80n)),
'Debt remains while liquidating',
);
currentTime = await setClockAndAdvanceNTimes(manualTimer, 2, startTime, 2n);
trace(`advanced time to `, currentTime);
notification = await E(vaultNotifier).getUpdateSince();
t.is(notification.value.vaultState, Phase.LIQUIDATED);
trace(t, 'debt gone');
t.truthy(await E(vaultSeat).hasExited());
const debtAmountAfter = await E(vault).getCurrentDebt();
const finalNotification = await E(vaultNotifier).getUpdateSince();
t.is(finalNotification.value.vaultState, Phase.LIQUIDATED);
t.deepEqual(finalNotification.value.locked, aeth.make(0n));
t.is(debtAmountAfter.value, 0n);
t.deepEqual(await E(vaultFactory).getRewardAllocation(), {
Minted: run.make(80n),
});
/** @type {UserSeat<string>} */
const closeSeat = await E(zoe).offer(E(vault).makeCloseInvitation());
await E(closeSeat).getOfferResult();
const closeProceeds = await E(closeSeat).getPayouts();
const collProceeds = await aeth.issuer.getAmountOf(closeProceeds.Collateral);
// Vault Holder got nothing
t.falsy(closeProceeds.Minted);
t.deepEqual(collProceeds, aeth.make(0n));
t.deepEqual(await E(vault).getCollateralAmount(), aeth.makeEmpty());
// Bidder bought 400 Aeth
await assertBidderPayout(t, bidderSeat, run, 320n, aeth, 400n);
await m.assertLike({
allocations: {
Aeth: undefined,
Fee: undefined,
},
});
});
test('price falls precipitously', async t => {
const { zoe, aeth, run, rates } = t.context;
t.context.interestTiming = {
chargingPeriod: 2n,
recordingPeriod: 10n,
};
// The borrower will deposit 4 Aeth, and ask to borrow 500 Minted. The
// PriceAuthority's initial quote is 180. The max loan on 4 Aeth would be 600
// (to make the margin 20%).
// The price falls to 130, so the loan will get liquidated. At that point, 4
// Aeth is worth 520, with a 5% margin, 546 is required. The auction sells at
// 85%, so the borrower gets something back
const manualTimer = buildManualTimer();
const services = await setupServices(
t,
makeRatio(600n, run.brand, 4n, aeth.brand),
aeth.make(900n),
manualTimer,
undefined,
500n,
{ StartFrequency: ONE_HOUR },
);
// we start with time=0, price=2200
const { vaultFactory, aethCollateralManager } = services.vaultFactory;
const {
reserveKit: { reserveCreatorFacet, reservePublicFacet },
auctioneerKit,
aethTestPriceAuthority,
} = services;
await E(reserveCreatorFacet).addIssuer(aeth.issuer, 'Aeth');
// Create a loan for 500 Minted with 4 aeth collateral
const collateralAmount = aeth.make(4n);
const wantMinted = run.make(500n);
/** @type {UserSeat<VaultKit>} */
const userSeat = await E(zoe).offer(
await E(aethCollateralManager).makeVaultInvitation(),
harden({
give: { Collateral: collateralAmount },
want: { Minted: wantMinted },
}),
harden({
Collateral: aeth.mint.mintPayment(collateralAmount),
}),
);
// A bidder places a bid //////////////////////////
const bidAmount = run.make(500n);
const desired = aeth.make(4n);
const bidderSeat = await bid(t, zoe, auctioneerKit, aeth, bidAmount, desired);
const {
vault,
publicNotifiers: { vault: vaultNotifier },
} = await legacyOfferResult(userSeat);
const debtAmount = await E(vault).getCurrentDebt();
const fee = ceilMultiplyBy(run.make(500n), rates.mintFee);
t.deepEqual(
debtAmount,
AmountMath.add(wantMinted, fee),
'borrower owes 525 Minted',
);
const { Minted: lentAmount } = await E(userSeat).getFinalAllocation();
t.deepEqual(lentAmount, wantMinted, 'received 470 Minted');
t.deepEqual(
await E(vault).getCollateralAmount(),
aeth.make(4n),
'vault holds 4 Collateral',
);
aethTestPriceAuthority.setPrice(makeRatio(130n, run.brand, 1n, aeth.brand));
await eventLoopIteration();
const { startTime, time } = await startAuctionClock(
auctioneerKit,
manualTimer,
);
const currentTime = time;
trace('time advanced to ', currentTime);
const assertDebtIs = async value => {
const debt = await E(vault).getCurrentDebt();
t.is(
debt.value,
BigInt(value),
`Expected debt ${debt.value} to be ${value}`,
);
};
const metricsTopic = await E.get(E(reservePublicFacet).getPublicTopics())
.metrics;
const m = await subscriptionTracker(t, metricsTopic);
await m.assertInitial(reserveInitialState(run.makeEmpty()));
await assertDebtIs(debtAmount.value);
await setClockAndAdvanceNTimes(manualTimer, 2, startTime, 2n);
t.deepEqual(
await E(vault).getCurrentDebt(),
run.makeEmpty(),
`Expected debt after liquidation to be zero`,
);
t.deepEqual(await E(vaultFactory).getRewardAllocation(), {
Minted: run.make(25n),
});
t.deepEqual(
await E(vault).getCollateralAmount(),
aeth.makeEmpty(),
'Collateral reduced after liquidation',
);
t.deepEqual(
await E(vault).getCollateralAmount(),
aeth.makeEmpty(),
'Excess collateral not returned due to shortfall',
);
const finalNotification = await E(vaultNotifier).getUpdateSince();
t.is(finalNotification.value.vaultState, Phase.LIQUIDATED);
// vault holds no debt after liquidation
t.is(finalNotification.value.debtSnapshot.debt.value, 0n);
/** @type {UserSeat<string>} */
const closeSeat = await E(zoe).offer(E(vault).makeCloseInvitation());
// closing with 64n Minted remaining in debt
await E(closeSeat).getOfferResult();
const closeProceeds = await E(closeSeat).getPayouts();
const collProceeds = await aeth.issuer.getAmountOf(closeProceeds.Collateral);
t.falsy(closeProceeds.Minted);
t.deepEqual(collProceeds, aeth.make(0n));
t.deepEqual(await E(vault).getCollateralAmount(), aeth.makeEmpty());
// Bidder bought 4 Aeth
await assertBidderPayout(t, bidderSeat, run, 58n, aeth, 4n);
});
// We'll make two loans, and trigger liquidation of one via price changes, and
// the other via interest charges. The interest rate is 40%. The liquidation
// margin is 103%. The priceAuthority will initially quote 10:1 Run:Aeth, and
// drop to 7:1. Both loans will initially be over collateralized 100%. Alice
// will withdraw enough of the overage that she'll get caught when prices drop.
// Bob will be charged interest, which will trigger liquidation.
test('liquidate two loans', async t => {
const { zoe, aeth, run, rates: defaultRates } = t.context;
// Add a vaultManager with 10000 aeth collateral at a 200 aeth/Minted rate
const rates = harden({
...defaultRates,
// charge 40% interest / year
interestRate: run.makeRatio(40n),
liquidationMargin: run.makeRatio(103n),
});
t.context.rates = rates;
// Interest is charged daily, and auctions are every week, so we'll charge
// interest a few times before the second auction.
t.context.interestTiming = {
chargingPeriod: ONE_DAY,
recordingPeriod: ONE_DAY,
};
const manualTimer = buildManualTimer();
const services = await setupServices(
t,
makeRatio(100n, run.brand, 10n, aeth.brand),
aeth.make(1n),
manualTimer,
ONE_WEEK,
500n,
);
const {
vaultFactory: { aethVaultManager, aethCollateralManager },
aethTestPriceAuthority,
reserveKit: { reserveCreatorFacet, reservePublicFacet },
auctioneerKit,
} = services;
await E(reserveCreatorFacet).addIssuer(aeth.issuer, 'Aeth');
const metricsTopic = await E.get(E(reservePublicFacet).getPublicTopics())
.metrics;
const m = await subscriptionTracker(t, metricsTopic);
await m.assertInitial(reserveInitialState(run.makeEmpty()));
let shortfallBalance = 0n;
const cm = await E(aethVaultManager).getPublicFacet();
const aethVaultMetrics = await vaultManagerMetricsTracker(t, cm);
await aethVaultMetrics.assertInitial({
// present
numActiveVaults: 0,
numLiquidatingVaults: 0,
totalCollateral: aeth.make(0n),
totalDebt: run.make(0n),
retainedCollateral: aeth.make(0n),
// running
numLiquidationsCompleted: 0,
numLiquidationsAborted: 0,
totalOverageReceived: run.make(0n),
totalProceedsReceived: run.make(0n),
totalCollateralSold: aeth.make(0n),
liquidatingCollateral: aeth.make(0n),
liquidatingDebt: run.make(0n),
totalShortfallReceived: run.make(0n),
lockedQuote: null,
});
// initial loans /////////////////////////////////////
// ALICE ////////////////////////////////////////////
// Create a loan for Alice for 5000 Minted with 1000 aeth collateral
// ratio is 4:1
const aliceCollateralAmount = aeth.make(1000n);
const aliceWantMinted = run.make(5000n);
/** @type {UserSeat<VaultKit>} */
const aliceVaultSeat = await E(zoe).offer(
await E(aethCollateralManager).makeVaultInvitation(),
harden({
give: { Collateral: aliceCollateralAmount },
want: { Minted: aliceWantMinted },
}),
harden({
Collateral: aeth.mint.mintPayment(aliceCollateralAmount),
}),
);
const {
vault: aliceVault,
publicNotifiers: { vault: aliceNotifier },
} = await legacyOfferResult(aliceVaultSeat);
const aliceDebtAmount = await E(aliceVault).getCurrentDebt();
const fee = ceilMultiplyBy(aliceWantMinted, rates.mintFee);
const aliceRunDebtLevel = AmountMath.add(aliceWantMinted, fee);
t.deepEqual(
aliceDebtAmount,
aliceRunDebtLevel,
'vault lent 5000 Minted + fees',
);
const { Minted: aliceLentAmount } =
await E(aliceVaultSeat).getFinalAllocation();
const aliceProceeds = await E(aliceVaultSeat).getPayouts();
t.deepEqual(aliceLentAmount, aliceWantMinted, 'received 5000 Minted');
trace(t, 'alice vault');
const aliceRunLent = await aliceProceeds.Minted;
t.truthy(
AmountMath.isEqual(
await E(run.issuer).getAmountOf(aliceRunLent),
aliceWantMinted,
),
);
let aliceUpdate = await E(aliceNotifier).getUpdateSince();
t.deepEqual(aliceUpdate.value.debtSnapshot.debt, aliceRunDebtLevel);
let totalDebt = 5250n;
await aethVaultMetrics.assertChange({
numActiveVaults: 1,
totalCollateral: { value: 1000n },
totalDebt: { value: totalDebt },
});
// BOB //////////////////////////////////////////////
// Create a loan for Bob for 630 Minted with 100 Aeth collateral
const bobCollateralAmount = aeth.make(100n);
const bobWantMinted = run.make(630n);
/** @type {UserSeat<VaultKit>} */
const bobVaultSeat = await E(zoe).offer(
await E(aethCollateralManager).makeVaultInvitation(),
harden({
give: { Collateral: bobCollateralAmount },
want: { Minted: bobWantMinted },
}),
harden({
Collateral: aeth.mint.mintPayment(bobCollateralAmount),
}),
);
const {
vault: bobVault,
publicNotifiers: { vault: bobNotifier },
} = await legacyOfferResult(bobVaultSeat);
const bobDebtAmount = await E(bobVault).getCurrentDebt();
const bobFee = ceilMultiplyBy(bobWantMinted, rates.mintFee);
const bobRunDebtLevel = AmountMath.add(bobWantMinted, bobFee);
t.deepEqual(bobDebtAmount, bobRunDebtLevel, 'vault lent 5000 Minted + fees');
const { Minted: bobLentAmount } = await E(bobVaultSeat).getFinalAllocation();
const bobProceeds = await E(bobVaultSeat).getPayouts();
t.deepEqual(bobLentAmount, bobWantMinted, 'received 5000 Minted');
trace(t, 'bob vault');
const bobRunLent = await bobProceeds.Minted;
t.truthy(
AmountMath.isEqual(
await E(run.issuer).getAmountOf(bobRunLent),
bobWantMinted,
),
);
let bobUpdate = await E(bobNotifier).getUpdateSince();
t.deepEqual(bobUpdate.value.debtSnapshot.debt, bobRunDebtLevel);
totalDebt += 630n + 32n;
await aethVaultMetrics.assertChange({
numActiveVaults: 2,
totalCollateral: { value: 1100n },
totalDebt: { value: totalDebt },
});
// reduce collateral /////////////////////////////////////
// Alice reduce collateral by 300. That leaves her at 700 * 10 > 1.05 * 5000.
// Prices will drop from 10 to 7, she'll be liquidated: 700 * 7 < 1.05 * 5000.
const collateralDecrement = aeth.make(300n);
const aliceReduceCollateralSeat = await E(zoe).offer(
E(aliceVault).makeAdjustBalancesInvitation(),
harden({
want: { Collateral: collateralDecrement },
}),
);
await E(aliceReduceCollateralSeat).getOfferResult();
const { Collateral: aliceWithdrawnAeth } = await E(
aliceReduceCollateralSeat,
).getFinalAllocation();
const proceeds4 = await E(aliceReduceCollateralSeat).getPayouts();
t.deepEqual(aliceWithdrawnAeth, aeth.make(300n));
const collateralWithdrawn = await proceeds4.Collateral;
t.truthy(
AmountMath.isEqual(
await E(aeth.issuer).getAmountOf(collateralWithdrawn),
collateralDecrement,
),
);
aliceUpdate = await E(aliceNotifier).getUpdateSince(aliceUpdate.updateCount);
t.deepEqual(aliceUpdate.value.debtSnapshot.debt, aliceRunDebtLevel);
trace(t, 'alice reduce collateral');
await aethVaultMetrics.assertChange({
totalCollateral: { value: 800n },
});
await E(aethTestPriceAuthority).setPrice(
makeRatio(70n, run.brand, 10n, aeth.brand),
);
trace(t, 'changed price to 7 RUN/Aeth');
// A BIDDER places a BID //////////////////////////
const bidAmount = run.make(10000n);
const desired = aeth.make(800n);
const bidderSeat = await bid(t, zoe, auctioneerKit, aeth, bidAmount, desired);
const { startTime: start1, time: now1 } = await startAuctionClock(
auctioneerKit,
manualTimer,
);
let currentTime = now1;
await aethVaultMetrics.assertChange({
lockedQuote: makeRatioFromAmounts(
aeth.make(1_000_000n),
run.make(7_000_000n),
),
});
// expect Alice to be liquidated because her collateral is too low.
aliceUpdate = await E(aliceNotifier).getUpdateSince(aliceUpdate.updateCount);
trace(t, 'alice liquidating?', aliceUpdate.value.vaultState);
t.is(aliceUpdate.value.vaultState, Phase.LIQUIDATING);
currentTime = await setClockAndAdvanceNTimes(manualTimer, 2, start1, 2n);
aliceUpdate = await E(aliceNotifier).getUpdateSince(aliceUpdate.updateCount);
t.is(aliceUpdate.value.vaultState, Phase.LIQUIDATED);
trace(t, 'alice liquidated');
totalDebt += 36n;
await aethVaultMetrics.assertChange({
numActiveVaults: 1,
numLiquidatingVaults: 1,
totalDebt: { value: totalDebt },
liquidatingCollateral: { value: 700n },
liquidatingDebt: { value: 5282n },
lockedQuote: null,
});
shortfallBalance += 137n;
await m.assertChange({
shortfallBalance: { value: shortfallBalance },
});
bobUpdate = await E(bobNotifier).getUpdateSince();
t.is(bobUpdate.value.vaultState, Phase.ACTIVE);
const { startTime: start2 } = await startAuctionClock(
auctioneerKit,
manualTimer,
);
totalDebt -= 5145n + shortfallBalance - 1n;
await aethVaultMetrics.assertChange({
liquidatingDebt: { value: 0n },
liquidatingCollateral: { value: 0n },
totalCollateral: { value: 100n },
totalDebt: { value: totalDebt },
numLiquidatingVaults: 0,
numLiquidationsCompleted: 1,
totalCollateralSold: { value: 700n },
totalProceedsReceived: { value: 5145n },
totalShortfallReceived: { value: shortfallBalance },
});
bobUpdate = await E(bobNotifier).getUpdateSince();
t.is(bobUpdate.value.vaultState, Phase.ACTIVE);
currentTime = await setClockAndAdvanceNTimes(manualTimer, 2, start2, 2n);
await aethVaultMetrics.assertChange({
lockedQuote: makeRatioFromAmounts(
aeth.make(1_000_000n),
run.make(7_000_000n),
),
});
// Bob's loan is now 777 Minted (including interest) on 100 Aeth, with the price
// at 7. 100 * 7 > 1.05 * 777. When interest is charged again, Bob should get
// liquidated.
const { startTime: start3, time: now3 } = await startAuctionClock(
auctioneerKit,
manualTimer,
);
totalDebt += 6n;
await aethVaultMetrics.assertChange({
lockedQuote: null,
totalDebt: { value: totalDebt },
});
totalDebt += 1n;
await aethVaultMetrics.assertChange({
lockedQuote: makeRatioFromAmounts(
aeth.make(1_000_000n),
run.make(7_000_000n),
),
totalDebt: { value: totalDebt },
});
totalDebt += 6n;
await aethVaultMetrics.assertChange({
liquidatingDebt: { value: 680n },
liquidatingCollateral: { value: 100n },
totalDebt: { value: totalDebt },
numActiveVaults: 0,
numLiquidatingVaults: 1,
lockedQuote: null,
});
currentTime = now3;
currentTime = await setClockAndAdvanceNTimes(manualTimer, 2, start3, ONE_DAY);
trace(t, 'finished auctions', currentTime);
bobUpdate = await E(bobNotifier).getUpdateSince();
t.is(bobUpdate.value.vaultState, Phase.LIQUIDATED);
totalDebt = 0n;
await aethVaultMetrics.assertChange({
liquidatingDebt: { value: 0n },
liquidatingCollateral: { value: 0n },
totalCollateral: { value: 0n },
totalDebt: { value: totalDebt },
numLiquidatingVaults: 0,
numLiquidationsCompleted: 2,
totalCollateralSold: { value: 792n },
totalProceedsReceived: { value: 5825n },
});