-
Notifications
You must be signed in to change notification settings - Fork 221
/
Copy pathvaultManager.js
1349 lines (1231 loc) · 46.7 KB
/
vaultManager.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
/**
* @file Vault Manager object manages vault-based debts for a collateral type.
*
* The responsibilities include:
*
* - opening a new vault backed by the collateral
* - publishing metrics on the vault economy for that collateral
* - charging interest on all active vaults
* - liquidating active vaults that have exceeded the debt ratio
*
* Once a vault is settled (liquidated or closed) it can still be used, traded,
* etc. but is no longer the concern of the manager. It can't be liquidated,
* have interest charged, or be counted in the metrics.
*
* Undercollateralized vaults can have their assets sent to the auctioneer to be
* liquidated. If the auction is unsuccessful, the liquidation may be
* reverted.
*/
/// <reference types="@agoric/zoe/exported" />
import { X, Fail, q, makeError } from '@endo/errors';
import { E } from '@endo/eventual-send';
import {
AmountMath,
AmountShape,
BrandShape,
NotifierShape,
RatioShape,
} from '@agoric/ertp';
import { makeTracer } from '@agoric/internal';
import { makeStoredNotifier, observeNotifier } from '@agoric/notifier';
import { appendToStoredArray } from '@agoric/store/src/stores/store-utils.js';
import {
M,
makeScalarBigMapStore,
makeScalarBigSetStore,
prepareExoClassKit,
provide,
} from '@agoric/vat-data';
import { TransferPartShape } from '@agoric/zoe/src/contractSupport/atomicTransfer.js';
import {
ceilMultiplyBy,
floorDivideBy,
getAmountIn,
getAmountOut,
makeEphemeraProvider,
makeRatio,
makeRecorderTopic,
offerTo,
SubscriberShape,
TopicsRecordShape,
} from '@agoric/zoe/src/contractSupport/index.js';
import { PriceQuoteShape, SeatShape } from '@agoric/zoe/src/typeGuards.js';
import { multiplyBy } from '@agoric/zoe/src/contractSupport/ratio.js';
import {
checkDebtLimit,
makeNatAmountShape,
quoteAsRatio,
} from '../contractSupport.js';
import { chargeInterest } from '../interest.js';
import { getLiquidatableVaults } from './liquidation.js';
import { calculateMinimumCollateralization, minimumPrice } from './math.js';
import { makePrioritizedVaults } from './prioritizedVaults.js';
import { Phase, prepareVault } from './vault.js';
import { calculateDistributionPlan } from './proceeds.js';
import { AuctionPFShape } from '../auction/auctioneer.js';
/**
* @import {EReturn} from '@endo/far';
* @import {PriceAuthority, PriceDescription, PriceQuote, PriceQuoteValue, PriceQuery,} from '@agoric/zoe/tools/types.js';
*/
const trace = makeTracer('VM');
/**
* Watch a notifier that isn't expected to fail or finish unless the vat hosting
* the notifier is upgraded. This watcher supports that by providing a
* straightforward way to get a replacement if the notifier breaks.
*
* @template T notifier topic
* @template {any[]} [A=unknown[]] arbitrary arguments
* @param {ERef<LatestTopic<T>>} notifierP
* @param {import('@agoric/swingset-liveslots').PromiseWatcher<T, A>} watcher
* @param {A} args
*/
export const watchQuoteNotifier = async (notifierP, watcher, ...args) => {
await undefined;
let updateCount;
for (;;) {
let value;
try {
({ value, updateCount } = await E(notifierP).getUpdateSince(updateCount));
watcher.onFulfilled && watcher.onFulfilled(value, ...args);
} catch (e) {
watcher.onRejected && watcher.onRejected(e, ...args);
break;
}
if (updateCount === undefined) {
watcher.onRejected &&
watcher.onRejected(Error('stream finished'), ...args);
break;
}
}
};
/** @import {NormalizedDebt} from './storeUtils.js' */
/** @import {RelativeTime} from '@agoric/time' */
// Metrics naming scheme: nouns are present values; past-participles are accumulative.
/**
* @typedef {object} MetricsNotification
* @property {Ratio | null} lockedQuote priceQuote that will be used for
* liquidation. Non-null from priceLock time until liquidation has taken
* place.
* @property {number} numActiveVaults present count of vaults
* @property {number} numLiquidatingVaults present count of liquidating vaults
* @property {Amount<'nat'>} totalCollateral present sum of collateral across
* all vaults
* @property {Amount<'nat'>} totalDebt present sum of debt across all vaults
* @property {Amount<'nat'>} retainedCollateral collateral held as a result of
* not returning excess refunds to owners of vaults liquidated with
* shortfalls
* @property {Amount<'nat'>} liquidatingCollateral present sum of collateral in
* vaults sent for liquidation
* @property {Amount<'nat'>} liquidatingDebt present sum of debt in vaults sent
* for liquidation
* @property {Amount<'nat'>} totalCollateralSold running sum of collateral sold
* in liquidation
* @property {Amount<'nat'>} totalOverageReceived running sum of overages,
* central received greater than debt
* @property {Amount<'nat'>} totalProceedsReceived running sum of minted
* received from liquidation
* @property {Amount<'nat'>} totalShortfallReceived running sum of shortfalls,
* minted received less than debt
* @property {number} numLiquidationsCompleted running count of liquidated
* vaults
* @property {number} numLiquidationsAborted running count of vault liquidations
* that were reverted.
*/
/**
* @typedef {{
* compoundedInterest: Ratio;
* interestRate: Ratio;
* latestInterestUpdate: Timestamp;
* }} AssetState
*
*
* @typedef {{
* getChargingPeriod: () => RelativeTime;
* getRecordingPeriod: () => RelativeTime;
* getDebtLimit: () => Amount<'nat'>;
* getInterestRate: () => Ratio;
* getLiquidationPadding: () => Ratio;
* getLiquidationMargin: () => Ratio;
* getLiquidationPenalty: () => Ratio;
* getMintFee: () => Ratio;
* getMinInitialDebt: () => Amount<'nat'>;
* }} GovernedParamGetters
*/
/**
* @typedef {Readonly<{
* debtMint: ZCFMint<'nat'>;
* collateralBrand: Brand<'nat'>;
* collateralUnit: Amount<'nat'>;
* descriptionScope: string;
* startTimeStamp: Timestamp;
* storageNode: StorageNode;
* }>} HeldParams
*/
/**
* @typedef {{
* assetTopicKit: import('@agoric/zoe/src/contractSupport/recorder.js').RecorderKit<AssetState>;
* debtBrand: Brand<'nat'>;
* liquidatingVaults: SetStore<Vault>;
* metricsTopicKit: import('@agoric/zoe/src/contractSupport/recorder.js').RecorderKit<MetricsNotification>;
* poolIncrementSeat: ZCFSeat;
* retainedCollateralSeat: ZCFSeat;
* unsettledVaults: MapStore<string, Vault>;
* }} ImmutableState
*/
/**
* @typedef {{
* compoundedInterest: Ratio;
* latestInterestUpdate: Timestamp;
* numLiquidationsCompleted: number;
* numLiquidationsAborted: number;
* totalCollateral: Amount<'nat'>;
* totalCollateralSold: Amount<'nat'>;
* totalDebt: Amount<'nat'>;
* liquidatingCollateral: Amount<'nat'>;
* liquidatingDebt: Amount<'nat'>;
* totalOverageReceived: Amount<'nat'>;
* totalProceedsReceived: Amount<'nat'>;
* totalShortfallReceived: Amount<'nat'>;
* vaultCounter: number;
* lockedQuote: PriceQuote | undefined;
* }} MutableState
*/
/**
* @type {(brand: Brand) => {
* prioritizedVaults: ReturnType<typeof makePrioritizedVaults>;
* storedQuotesNotifier: import('@agoric/notifier').StoredNotifier<PriceQuote>;
* storedCollateralQuote: PriceQuote | null;
* }}
*/
// any b/c will be filled after start()
const collateralEphemera = makeEphemeraProvider(() => /** @type {any} */ ({}));
/**
* @param {import('@agoric/swingset-liveslots').Baggage} baggage
* @param {{
* zcf: import('./vaultFactory.js').VaultFactoryZCF;
* marshaller: ERef<Marshaller>;
* makeRecorderKit: import('@agoric/zoe/src/contractSupport/recorder.js').MakeRecorderKit;
* makeERecorderKit: import('@agoric/zoe/src/contractSupport/recorder.js').MakeERecorderKit;
* factoryPowers: import('./vaultDirector.js').FactoryPowersFacet;
* }} powers
*/
export const prepareVaultManagerKit = (
baggage,
{ zcf, marshaller, makeRecorderKit, factoryPowers },
) => {
const { priceAuthority, timerService, reservePublicFacet } = zcf.getTerms();
const watchedBrands = new Set();
const makeVault = prepareVault(baggage, makeRecorderKit, zcf);
/**
* @param {HeldParams & { metricsStorageNode: StorageNode }} params
* @returns {HeldParams & ImmutableState & MutableState}
*/
const initState = params => {
const {
debtMint,
collateralBrand,
metricsStorageNode,
startTimeStamp,
storageNode,
} = params;
const debtBrand = debtMint.getIssuerRecord().brand;
/** @type {ImmutableState} */
const immutable = {
debtBrand,
poolIncrementSeat: zcf.makeEmptySeatKit().zcfSeat,
/**
* Vaults that have been sent for liquidation. When we get proceeds (or
* lack thereof) back from the liquidator, we will allocate them among the
* vaults.
*
* @type {SetStore<Vault>}
*/
liquidatingVaults: makeScalarBigSetStore('liquidatingVaults', {
durable: true,
}),
assetTopicKit: makeRecorderKit(storageNode),
metricsTopicKit: makeRecorderKit(metricsStorageNode),
// TODO(#7074) not used while liquidation is disabled. Reinstate with #7074
retainedCollateralSeat: zcf.makeEmptySeatKit().zcfSeat,
unsettledVaults: makeScalarBigMapStore('orderedVaultStore', {
durable: true,
}),
};
const zeroCollateral = AmountMath.makeEmpty(collateralBrand, 'nat');
const zeroDebt = AmountMath.makeEmpty(debtBrand, 'nat');
return harden({
...params,
...immutable,
compoundedInterest: makeRatio(100n, debtBrand), // starts at 1.0, no interest
latestInterestUpdate: startTimeStamp,
numLiquidationsCompleted: 0,
numLiquidationsAborted: 0,
totalCollateral: zeroCollateral,
totalCollateralSold: zeroCollateral,
totalDebt: zeroDebt,
liquidatingCollateral: zeroCollateral,
liquidatingDebt: zeroDebt,
totalOverageReceived: zeroDebt,
totalProceedsReceived: zeroDebt,
totalShortfallReceived: zeroDebt,
vaultCounter: 0,
lockedQuote: undefined,
});
};
const makeVaultManagerKitInternal = prepareExoClassKit(
baggage,
'VaultManagerKit',
{
collateral: M.interface('collateral', {
makeVaultInvitation: M.call().returns(M.promise()),
getPublicTopics: M.call().returns(TopicsRecordShape),
getQuotes: M.call().returns(NotifierShape),
getCompoundedInterest: M.call().returns(RatioShape),
}),
helper: M.interface(
'helper',
// not exposed so sloppy okay
{},
{ sloppy: true },
),
manager: M.interface('manager', {
getGovernedParams: M.call().returns(M.remotable('governedParams')),
maxDebtFor: M.call(AmountShape).returns(AmountShape),
mintAndTransfer: M.call(
SeatShape,
AmountShape,
AmountShape,
M.arrayOf(TransferPartShape),
).returns(),
burn: M.call(AmountShape, SeatShape).returns(),
getAssetSubscriber: M.call().returns(SubscriberShape),
getCollateralBrand: M.call().returns(BrandShape),
getDebtBrand: M.call().returns(BrandShape),
getCompoundedInterest: M.call().returns(RatioShape),
scopeDescription: M.call(M.string()).returns(M.string()),
handleBalanceChange: M.call(
AmountShape,
AmountShape,
M.string(),
M.string(),
M.remotable('vault'),
).returns(),
}),
self: M.interface('self', {
getGovernedParams: M.call().returns(M.remotable('governedParams')),
makeVaultKit: M.call(SeatShape).returns(M.promise()),
getCollateralQuote: M.call().returns(PriceQuoteShape),
getPublicFacet: M.call().returns(M.remotable('publicFacet')),
lockOraclePrices: M.call().returns(PriceQuoteShape),
liquidateVaults: M.call(M.eref(AuctionPFShape)).returns(M.promise()),
}),
},
initState,
{
collateral: {
makeVaultInvitation() {
const { facets } = this;
const { collateralBrand, debtBrand } = this.state;
return zcf.makeInvitation(
seat => this.facets.self.makeVaultKit(seat),
facets.manager.scopeDescription('MakeVault'),
undefined,
M.splitRecord({
give: {
Collateral: makeNatAmountShape(collateralBrand),
},
want: {
Minted: makeNatAmountShape(debtBrand),
},
}),
);
},
getQuotes() {
const ephemera = collateralEphemera(this.state.collateralBrand);
return ephemera.storedQuotesNotifier;
},
getCompoundedInterest() {
return this.state.compoundedInterest;
},
getPublicTopics() {
const { assetTopicKit, metricsTopicKit } = this.state;
return harden({
asset: makeRecorderTopic(
'State of the assets managed',
assetTopicKit,
),
metrics: makeRecorderTopic(
'Vault Factory metrics',
metricsTopicKit,
),
});
},
},
// Some of these could go in closures but are kept on a facet anticipating future durability options.
helper: {
/** Start non-durable processes (or restart if needed after vat restart) */
start() {
const { state, facets } = this;
trace(state.collateralBrand, 'helper.start()', state.vaultCounter);
const { collateralBrand, unsettledVaults } = state;
const ephemera = collateralEphemera(collateralBrand);
ephemera.prioritizedVaults = makePrioritizedVaults(unsettledVaults);
trace('helper.start() making periodNotifier');
const periodNotifier = E(timerService).makeNotifier(
0n,
factoryPowers
.getGovernedParams(collateralBrand)
.getChargingPeriod(),
);
trace('helper.start() starting observe periodNotifier');
void observeNotifier(periodNotifier, {
updateState: updateTime =>
facets.helper
.chargeAllVaults(updateTime)
.catch(e =>
console.error('🚨 vaultManager failed to charge interest', e),
),
fail: reason => {
zcf.shutdownWithFailure(
makeError(X`Unable to continue without a timer: ${reason}`),
);
},
finish: done => {
zcf.shutdownWithFailure(
makeError(X`Unable to continue without a timer: ${done}`),
);
},
});
void facets.helper.ensureQuoteNotifierWatched();
trace('helper.start() done');
},
ensureQuoteNotifierWatched() {
const { state } = this;
const { collateralBrand, collateralUnit, debtBrand, storageNode } =
state;
if (watchedBrands.has(collateralBrand)) {
return;
}
watchedBrands.add(collateralBrand);
const ephemera = collateralEphemera(collateralBrand);
const quoteNotifierP = E(priceAuthority).makeQuoteNotifier(
collateralUnit,
debtBrand,
);
void E.when(
quoteNotifierP,
quoteNotifier => {
// @ts-expect-error XXX quotes
ephemera.storedQuotesNotifier = makeStoredNotifier(
// @ts-expect-error XXX quotes
quoteNotifier,
E(storageNode).makeChildNode('quotes'),
marshaller,
);
trace(
'helper.start() awaiting observe storedQuotesNotifier',
collateralBrand,
);
// NB: upon restart, there may not be a price for a while. If manager
// operations are permitted, ones that depend on price information
// will throw. See https://github.com/Agoric/agoric-sdk/issues/4317
const quoteWatcher = harden({
onFulfilled(value) {
trace('watcher updated price', value);
ephemera.storedCollateralQuote = value;
},
onRejected() {
// NOTE: drastic action, if the quoteNotifier fails, we don't know
// the value of the asset, nor do we know how long we'll be in
// ignorance. Best choice is to disable actions that require
// prices and restart when we have a new price. If we restart the
// notifier immediately, we'll trigger an infinite loop, so try
// to restart each time we get a request.
ephemera.storedCollateralQuote = null;
watchedBrands.delete(collateralBrand);
},
});
void watchQuoteNotifier(quoteNotifier, quoteWatcher);
},
e => {
trace('makeQuoteNotifier failed, resetting', e);
ephemera.storedCollateralQuote = null;
watchedBrands.delete(collateralBrand);
},
);
},
/** @param {Timestamp} updateTime */
async chargeAllVaults(updateTime) {
const { state, facets } = this;
const { collateralBrand, debtMint, poolIncrementSeat } = state;
trace(collateralBrand, 'chargeAllVaults', {
updateTime,
});
const interestRate = factoryPowers
.getGovernedParams(collateralBrand)
.getInterestRate();
// Update state with the results of charging interest
const changes = chargeInterest(
{
mint: debtMint,
mintAndTransferWithFee: factoryPowers.mintAndTransfer,
poolIncrementSeat,
seatAllocationKeyword: 'Minted',
},
{
interestRate,
chargingPeriod: factoryPowers
.getGovernedParams(collateralBrand)
.getChargingPeriod(),
recordingPeriod: factoryPowers
.getGovernedParams(collateralBrand)
.getRecordingPeriod(),
},
{
latestInterestUpdate: state.latestInterestUpdate,
compoundedInterest: state.compoundedInterest,
totalDebt: state.totalDebt,
},
updateTime,
);
state.compoundedInterest = changes.compoundedInterest;
state.latestInterestUpdate = changes.latestInterestUpdate;
state.totalDebt = changes.totalDebt;
return facets.helper.assetNotify();
},
assetNotify() {
const { state } = this;
const { collateralBrand, assetTopicKit } = state;
const interestRate = factoryPowers
.getGovernedParams(collateralBrand)
.getInterestRate();
/** @type {AssetState} */
const payload = harden({
compoundedInterest: state.compoundedInterest,
interestRate,
latestInterestUpdate: state.latestInterestUpdate,
});
return assetTopicKit.recorder.write(payload);
},
burnToCoverDebt(debt, proceeds, seat) {
const { state } = this;
if (AmountMath.isGTE(proceeds, debt)) {
factoryPowers.burnDebt(debt, seat);
state.totalDebt = AmountMath.subtract(state.totalDebt, debt);
} else {
factoryPowers.burnDebt(proceeds, seat);
state.totalDebt = AmountMath.subtract(state.totalDebt, proceeds);
}
state.totalProceedsReceived = AmountMath.add(
state.totalProceedsReceived,
proceeds,
);
},
sendToReserve(penalty, seat, seatKeyword = 'Collateral') {
const invitation =
E(reservePublicFacet).makeAddCollateralInvitation();
trace('Sending to reserve: ', penalty);
// don't wait for response
void E.when(invitation, invite => {
const proposal = { give: { Collateral: penalty } };
return offerTo(
zcf,
invite,
{ [seatKeyword]: 'Collateral' },
proposal,
seat,
);
}).catch(reason => {
console.error('sendToReserve failed', reason);
});
},
markLiquidating(debt, collateral) {
const { state } = this;
state.liquidatingCollateral = AmountMath.add(
state.liquidatingCollateral,
collateral,
);
state.liquidatingDebt = AmountMath.add(state.liquidatingDebt, debt);
},
/**
* @param {Amount<'nat'>} debt
* @param {Amount<'nat'>} collateral
* @param {Amount<'nat'>} overage
* @param {Amount<'nat'>} shortfall
*/
markDoneLiquidating(debt, collateral, overage, shortfall) {
const { state } = this;
// update liquidation state
state.liquidatingCollateral = AmountMath.subtract(
state.liquidatingCollateral,
collateral,
);
state.liquidatingDebt = AmountMath.subtract(
state.liquidatingDebt,
debt,
);
// record shortfall and proceeds
// cumulative values
state.totalOverageReceived = AmountMath.add(
state.totalOverageReceived,
overage,
);
state.totalShortfallReceived = AmountMath.add(
state.totalShortfallReceived,
shortfall,
);
state.totalDebt = AmountMath.subtract(state.totalDebt, shortfall);
E.when(
factoryPowers.getShortfallReporter(),
reporter => E(reporter).increaseLiquidationShortfall(shortfall),
err =>
console.error(
'🛠️ getShortfallReporter() failed during liquidation; repair by updating governance',
err,
),
).catch(err => {
console.error('🚨 failed to report liquidation shortfall', err);
});
},
writeMetrics() {
const { state } = this;
const { collateralBrand, retainedCollateralSeat, metricsTopicKit } =
state;
const { prioritizedVaults } = collateralEphemera(collateralBrand);
const retainedCollateral =
retainedCollateralSeat.getCurrentAllocation()?.Collateral ??
AmountMath.makeEmpty(collateralBrand, 'nat');
const quote = state.lockedQuote;
const lockedQuoteRatio = quote
? quoteAsRatio(quote.quoteAmount.value[0])
: null;
/** @type {MetricsNotification} */
const payload = harden({
numActiveVaults: prioritizedVaults.getCount(),
numLiquidatingVaults: state.liquidatingVaults.getSize(),
totalCollateral: state.totalCollateral,
totalDebt: state.totalDebt,
retainedCollateral,
numLiquidationsCompleted: state.numLiquidationsCompleted,
numLiquidationsAborted: state.numLiquidationsAborted,
totalCollateralSold: state.totalCollateralSold,
liquidatingCollateral: state.liquidatingCollateral,
liquidatingDebt: state.liquidatingDebt,
totalOverageReceived: state.totalOverageReceived,
totalProceedsReceived: state.totalProceedsReceived,
totalShortfallReceived: state.totalShortfallReceived,
lockedQuote: lockedQuoteRatio,
});
return E(metricsTopicKit.recorder).write(payload);
},
/**
* This is designed to tolerate an incomplete plan, in case
* calculateDistributionPlan encounters an error during its calculation.
* We don't have a way to induce such errors in CI so we've done so
* manually in dev and verified this function recovers as expected.
*
* @param {AmountKeywordRecord} proceeds
* @param {Amount<'nat'>} totalDebt
* @param {Pick<PriceQuote, 'quoteAmount'>} oraclePriceAtStart
* @param {MapStore<
* Vault,
* { collateralAmount: Amount<'nat'>; debtAmount: Amount<'nat'> }
* >} vaultData
* @param {Amount<'nat'>} totalCollateral
*/
planProceedsDistribution(
proceeds,
totalDebt,
oraclePriceAtStart,
vaultData,
totalCollateral,
) {
const { state, facets } = this;
const { Collateral: collateralProceeds } = proceeds;
/** @type {Amount<'nat'>} */
const collateralSold = AmountMath.subtract(
totalCollateral,
collateralProceeds,
);
state.totalCollateralSold = AmountMath.add(
state.totalCollateralSold,
collateralSold,
);
const penaltyRate = facets.self
.getGovernedParams()
.getLiquidationPenalty();
const bestToWorst = [...vaultData.entries()].reverse();
// unzip the entry tuples
const vaultsInPlan = /** @type {Vault[]} */ ([]);
const vaultsBalances =
/** @type {import('./proceeds.js').VaultBalances[]} */ ([]);
for (const [vault, balances] of bestToWorst) {
vaultsInPlan.push(vault);
vaultsBalances.push({
collateral: balances.collateralAmount,
// if interest accrued during sale, the current debt will be higher
presaleDebt: balances.debtAmount,
currentDebt: vault.getCurrentDebt(),
});
}
harden(vaultsInPlan);
harden(vaultsBalances);
const plan = calculateDistributionPlan({
proceeds,
totalDebt,
totalCollateral,
oraclePriceAtStart: oraclePriceAtStart.quoteAmount.value[0],
vaultsBalances,
penaltyRate,
});
return { plan, vaultsInPlan };
},
/**
* This is designed to tolerate an incomplete plan, in case
* calculateDistributionPlan encounters an error during its calculation.
* We don't have a way to induce such errors in CI so we've done so
* manually in dev and verified this function recovers as expected.
*
* @param {object} obj
* @param {import('./proceeds.js').DistributionPlan} obj.plan
* @param {Vault[]} obj.vaultsInPlan
* @param {ZCFSeat} obj.liqSeat
* @param {Amount<'nat'>} obj.totalCollateral
* @param {Amount<'nat'>} obj.totalDebt
* @returns {void}
*/
distributeProceeds({
plan,
vaultsInPlan,
liqSeat,
totalCollateral,
totalDebt,
}) {
const { state, facets } = this;
// Putting all the rearrangements after the loop ensures that errors
// in the calculations don't result in paying back some vaults and
// leaving others hanging.
if (plan.transfersToVault.length > 0) {
const transfers = plan.transfersToVault.map(
([vaultIndex, amounts]) =>
/** @type {TransferPart} */ ([
liqSeat,
vaultsInPlan[vaultIndex].getVaultSeat(),
amounts,
]),
);
zcf.atomicRearrange(harden(transfers));
}
const { prioritizedVaults } = collateralEphemera(
totalCollateral.brand,
);
state.numLiquidationsAborted += plan.vaultsToReinstate.length;
for (const vaultIndex of plan.vaultsToReinstate) {
const vault = vaultsInPlan[vaultIndex];
const vaultId = vault.abortLiquidation();
prioritizedVaults.addVault(vaultId, vault);
state.liquidatingVaults.delete(vault);
}
if (!AmountMath.isEmpty(plan.phantomDebt)) {
state.totalDebt = AmountMath.subtract(
state.totalDebt,
plan.phantomDebt,
);
}
facets.helper.burnToCoverDebt(
plan.debtToBurn,
plan.mintedProceeds,
liqSeat,
);
if (!AmountMath.isEmpty(plan.mintedForReserve)) {
facets.helper.sendToReserve(
plan.mintedForReserve,
liqSeat,
'Minted',
);
}
// send all that's left in the seat
const collateralInLiqSeat = liqSeat.getCurrentAllocation().Collateral;
if (!AmountMath.isEmpty(collateralInLiqSeat)) {
facets.helper.sendToReserve(collateralInLiqSeat, liqSeat);
}
// if it didn't match what was expected, report
if (!AmountMath.isEqual(collateralInLiqSeat, plan.collatRemaining)) {
console.error(
`⚠️ Excess collateral remaining sent to reserve. Expected ${q(
plan.collatRemaining,
)}, sent ${q(collateralInLiqSeat)}`,
);
}
// 'totalCollateralSold' is only for this liquidation event
// 'state.totalCollateralSold' represents all active vaults
const actualCollateralSold = plan.actualCollateralSold;
state.totalCollateral = AmountMath.isEmpty(actualCollateralSold)
? AmountMath.subtract(state.totalCollateral, totalCollateral)
: AmountMath.subtract(state.totalCollateral, actualCollateralSold);
facets.helper.markDoneLiquidating(
totalDebt,
totalCollateral,
plan.overage,
plan.shortfallToReserve,
);
// liqSeat should be empty at this point, except that funds are sent
// asynchronously to the reserve.
},
},
manager: {
getGovernedParams() {
const { collateralBrand } = this.state;
return factoryPowers.getGovernedParams(collateralBrand);
},
/**
* Look up the most recent price authority price to determine the max
* debt this manager config will allow for the collateral.
*
* @param {Amount<'nat'>} collateralAmount
*/
maxDebtFor(collateralAmount) {
const { state, facets } = this;
const { collateralBrand } = state;
const { storedCollateralQuote } = collateralEphemera(collateralBrand);
if (!storedCollateralQuote) {
facets.helper.ensureQuoteNotifierWatched();
// it might take an arbitrary amount of time to get a new quote
throw Fail`maxDebtFor called before a collateral quote was available for ${collateralBrand}`;
}
// use the lower price to prevent vault adjustments that put them imminently underwater
const collateralPrice = minimumPrice(
storedCollateralQuote,
this.state.lockedQuote,
);
const collatlVal = ceilMultiplyBy(collateralAmount, collateralPrice);
const minimumCollateralization = calculateMinimumCollateralization(
factoryPowers
.getGovernedParams(collateralBrand)
.getLiquidationMargin(),
factoryPowers
.getGovernedParams(collateralBrand)
.getLiquidationPadding(),
);
// floorDivide because we want the debt ceiling lower
return floorDivideBy(collatlVal, minimumCollateralization);
},
/** @type {MintAndTransfer} */
mintAndTransfer(mintReceiver, toMint, fee, transfers) {
const { state } = this;
const { collateralBrand, totalDebt } = state;
checkDebtLimit(
factoryPowers.getGovernedParams(collateralBrand).getDebtLimit(),
totalDebt,
toMint,
);
factoryPowers.mintAndTransfer(mintReceiver, toMint, fee, transfers);
},
/**
* @param {Amount<'nat'>} toBurn
* @param {ZCFSeat} seat
*/
burn(toBurn, seat) {
const { state } = this;
const { collateralBrand } = this.state;
trace(collateralBrand, 'burn', {
toBurn,
totalDebt: state.totalDebt,
});
factoryPowers.burnDebt(toBurn, seat);
},
getAssetSubscriber() {
return this.state.assetTopicKit.subscriber;
},
getCollateralBrand() {
const { collateralBrand } = this.state;
return collateralBrand;
},
getDebtBrand() {
const { debtBrand } = this.state;
return debtBrand;
},
/**
* Prepend with an identifier of this vault manager
*
* @param {string} base
*/
scopeDescription(base) {
const { descriptionScope } = this.state;
return `${descriptionScope}: ${base}`;
},
/** coefficient on existing debt to calculate new debt */
getCompoundedInterest() {
return this.state.compoundedInterest;
},
/**
* Called by a vault when its balances change.
*
* @param {NormalizedDebt} oldDebtNormalized
* @param {Amount<'nat'>} oldCollateral
* @param {VaultId} vaultId
* @param {import('./vault.js').VaultPhase} vaultPhase at the end of
* whatever change updated balances
* @param {Vault} vault
* @returns {void}
*/
handleBalanceChange(
oldDebtNormalized,
oldCollateral,
vaultId,
vaultPhase,
vault,
) {
const { state, facets } = this;
// the manager holds only vaults that can accrue interest or be liquidated;
// i.e. vaults that have debt. The one exception is at the outset when
// a vault has been added to the manager but not yet accounted for.
const settled =
AmountMath.isEmpty(oldDebtNormalized) &&
vaultPhase !== Phase.ACTIVE;
trace('handleBalanceChange', {
oldDebtNormalized,
oldCollateral,
vaultId,
vaultPhase,
vault,
settled,
});
const { prioritizedVaults } = collateralEphemera(
state.collateralBrand,
);
if (settled) {
assert(
!prioritizedVaults.hasVaultByAttributes(
oldDebtNormalized,
oldCollateral,
vaultId,
),
'Settled vaults must not be retained in storage',
);
return;
}
const isNew = AmountMath.isEmpty(oldDebtNormalized);
trace(state.collateralBrand, { isNew });
if (!isNew) {
// its position in the queue is no longer valid
const vaultInStore = prioritizedVaults.removeVaultByAttributes(
oldDebtNormalized,
oldCollateral,
vaultId,
);
assert(
vault === vaultInStore,
'handleBalanceChange for two different vaults',
);
trace('removed', vault, vaultId);
}