-
Notifications
You must be signed in to change notification settings - Fork 212
/
vaultManager.js
846 lines (777 loc) · 27.4 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
/* eslint-disable consistent-return */
// @ts-check
/**
* @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.
*/
import '@agoric/zoe/exported.js';
import { AmountMath } from '@agoric/ertp';
import { Nat } from '@agoric/nat';
import { makeStoredPublishKit, observeNotifier } from '@agoric/notifier';
import { defineKindMulti, pickFacet } from '@agoric/vat-data';
import {
assertProposalShape,
ceilDivideBy,
ceilMultiplyBy,
floorDivideBy,
getAmountIn,
getAmountOut,
makeRatio,
makeRatioFromAmounts,
} from '@agoric/zoe/src/contractSupport/index.js';
import { E } from '@endo/eventual-send';
import { checkDebtLimit, makeMetricsPublisherKit } from '../contractSupport.js';
import { chargeInterest } from '../interest.js';
import { makeTracer } from '../makeTracer.js';
import { liquidate } from './liquidation.js';
import { makePrioritizedVaults } from './prioritizedVaults.js';
import { makeVault, Phase } from './vault.js';
const { details: X } = assert;
const trace = makeTracer('VM');
/** @typedef {import('./storeUtils.js').NormalizedDebt} NormalizedDebt */
// Metrics naming scheme: nouns are present values; past-participles are accumulative.
/**
* @typedef {object} MetricsNotification
*
* @property {number} numVaults present count of 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'>} totalCollateralSold running sum of collateral sold in liquidation // totalCollateralSold
* @property {Amount<'nat'>} totalOverageReceived running sum of overages, central received greater than debt
* @property {Amount<'nat'>} totalProceedsReceived running sum of central received from liquidation
* @property {Amount<'nat'>} totalShortfallReceived running sum of shortfalls, central received less than debt
* @property {number} numLiquidationsCompleted running count of liquidations
*/
/**
* @typedef {{
* compoundedInterest: Ratio,
* interestRate: Ratio,
* latestInterestUpdate: bigint,
* liquidatorInstance?: Instance,
* }} AssetState
*
* @typedef {{
* getChargingPeriod: () => bigint,
* getRecordingPeriod: () => bigint,
* getDebtLimit: () => Amount<'nat'>,
* getInterestRate: () => Ratio,
* getLiquidationMargin: () => Ratio,
* getLiquidationPenalty: () => Ratio,
* getLoanFee: () => Ratio,
* }} GovernedParamGetters
*/
/**
* @typedef {Readonly<{
* assetSubscriber: Subscriber<AssetState>,
* assetPublisher: Publisher<AssetState>,
* collateralBrand: Brand<'nat'>,
* debtBrand: Brand<'nat'>,
* debtMint: ZCFMint<'nat'>,
* factoryPowers: import('./vaultDirector.js').FactoryPowersFacet,
* marshaller?: ERef<Marshaller>,
* metricsPublication: IterationObserver<MetricsNotification>,
* metricsSubscription: StoredSubscription<MetricsNotification>,
* periodNotifier: ERef<Notifier<bigint>>,
* poolIncrementSeat: ZCFSeat,
* priceAuthority: ERef<PriceAuthority>,
* prioritizedVaults: ReturnType<typeof makePrioritizedVaults>,
* storageNode?: ERef<StorageNode>,
* zcf: import('./vaultFactory.js').VaultFactoryZCF,
* }>} ImmutableState
*/
/**
* @typedef {{
* compoundedInterest: Ratio,
* latestInterestUpdate: bigint,
* liquidator?: Liquidator
* liquidatorInstance?: Instance
* numLiquidationsCompleted: number,
* totalCollateral: Amount<'nat'>,
* totalCollateralSold: Amount<'nat'>,
* totalDebt: Amount<'nat'>,
* totalOverageReceived: Amount<'nat'>,
* totalProceedsReceived: Amount<'nat'>,
* totalShortfallReceived: Amount<'nat'>,
* vaultCounter: number,
* }} MutableState
*/
/**
* @typedef {Readonly<{
* state: ImmutableState & MutableState,
* facets: {
* collateral: import('@agoric/vat-data/src/types').KindFacet<typeof collateralBehavior>,
* helper: import('@agoric/vat-data/src/types').KindFacet<typeof helperBehavior>,
* manager: import('@agoric/vat-data/src/types').KindFacet<typeof managerBehavior>,
* self: import('@agoric/vat-data/src/types').KindFacet<typeof selfBehavior>,
* }
* }>} MethodContext
*/
// FIXME https://github.com/Agoric/agoric-sdk/issues/5622
let liquidationQueueing = false;
let outstandingQuote = null;
/**
* Create state for the Vault Manager kind
*
* @param {import('./vaultFactory.js').VaultFactoryZCF} zcf
* @param {ZCFMint<'nat'>} debtMint
* @param {Brand} collateralBrand
* @param {ERef<PriceAuthority>} priceAuthority
* @param {import('./vaultDirector.js').FactoryPowersFacet} factoryPowers
* @param {ERef<TimerService>} timerService
* @param {Timestamp} startTimeStamp
* @param {ERef<StorageNode>} [storageNode]
* @param {ERef<Marshaller>} [marshaller]
*/
const initState = (
zcf,
debtMint,
collateralBrand,
priceAuthority,
factoryPowers,
timerService,
startTimeStamp,
storageNode,
marshaller,
) => {
const periodNotifier = E(timerService).makeNotifier(
0n,
factoryPowers.getGovernedParams().getChargingPeriod(),
);
const debtBrand = debtMint.getIssuerRecord().brand;
const zeroCollateral = AmountMath.makeEmpty(collateralBrand, 'nat');
const zeroDebt = AmountMath.makeEmpty(debtBrand, 'nat');
const { metricsPublication, metricsSubscription } = makeMetricsPublisherKit(
storageNode,
marshaller,
);
/** @type {PublishKit<AssetState>} */
const { publisher: assetPublisher, subscriber: assetSubscriber } =
makeStoredPublishKit(storageNode, marshaller);
/** @type {ImmutableState} */
const fixed = {
assetSubscriber,
assetPublisher,
collateralBrand,
debtBrand,
debtMint,
factoryPowers,
metricsSubscription,
metricsPublication,
periodNotifier,
poolIncrementSeat: zcf.makeEmptySeatKit().zcfSeat,
priceAuthority,
/**
* A store for vaultKits prioritized by their collaterization ratio.
*/
prioritizedVaults: makePrioritizedVaults(),
zcf,
};
const compoundedInterest = makeRatio(100n, fixed.debtBrand); // starts at 1.0, no interest
// timestamp of most recent update to interest
const latestInterestUpdate = startTimeStamp;
assetPublisher.publish(
harden({
compoundedInterest,
interestRate: fixed.factoryPowers.getGovernedParams().getInterestRate(),
latestInterestUpdate,
}),
);
/** @type {MutableState & ImmutableState} */
const state = {
...fixed,
compoundedInterest,
debtBrand: fixed.debtBrand,
latestInterestUpdate,
liquidator: undefined,
liquidatorInstance: undefined,
numLiquidationsCompleted: 0,
totalCollateral: zeroCollateral,
totalDebt: zeroDebt,
totalOverageReceived: zeroDebt,
totalProceedsReceived: zeroDebt,
totalCollateralSold: zeroCollateral,
totalShortfallReceived: zeroDebt,
vaultCounter: 0,
};
return state;
};
/**
* Threshold to alert when the price level falls enough that the vault
* with the highest debt to collateral ratio will no longer be valued at the
* liquidationMargin above its debt.
*
* @param {Ratio} highestDebtRatio
* @param {Ratio} liquidationMargin
*/
const liquidationThreshold = (highestDebtRatio, liquidationMargin) =>
ceilMultiplyBy(
highestDebtRatio.numerator, // debt
liquidationMargin,
);
// Some of these could go in closures but are kept on a facet anticipating future durability options.
const helperBehavior = {
/**
* @param {MethodContext} context
* @param {bigint} updateTime
* @param {ZCFSeat} poolIncrementSeat
*/
chargeAllVaults: async ({ state, facets }, updateTime, poolIncrementSeat) => {
trace('chargeAllVaults', { updateTime });
const interestRate = state.factoryPowers
.getGovernedParams()
.getInterestRate();
// Update state with the results of charging interest
const changes = chargeInterest(
{
mint: state.debtMint,
mintAndReallocateWithFee: state.factoryPowers.mintAndReallocate,
poolIncrementSeat,
seatAllocationKeyword: 'RUN',
},
{
interestRate,
chargingPeriod: state.factoryPowers
.getGovernedParams()
.getChargingPeriod(),
recordingPeriod: state.factoryPowers
.getGovernedParams()
.getRecordingPeriod(),
},
{
latestInterestUpdate: state.latestInterestUpdate,
compoundedInterest: state.compoundedInterest,
totalDebt: state.totalDebt,
},
updateTime,
);
state.compoundedInterest = changes.compoundedInterest;
state.latestInterestUpdate = changes.latestInterestUpdate;
state.totalDebt = changes.totalDebt;
facets.helper.assetNotify();
trace('chargeAllVaults complete');
// price to check against has changed
return facets.helper.reschedulePriceCheck();
},
/** @param {MethodContext} context */
assetNotify: ({ state }) => {
const interestRate = state.factoryPowers
.getGovernedParams()
.getInterestRate();
/** @type {AssetState} */
const payload = harden({
compoundedInterest: state.compoundedInterest,
interestRate,
latestInterestUpdate: state.latestInterestUpdate,
// NB: the liquidator is determined by governance but the resulting
// instance is a concern of the manager. The param manager knows only
// about the installation and terms of the liqudation contract. We could
// have another notifier for state downstream of governance changes, but
// that doesn't seem to be cost-effective.
liquidatorInstance: state.liquidatorInstance,
});
state.assetPublisher.publish(payload);
},
/** @param {MethodContext} context */
updateMetrics: ({ state }) => {
/** @type {MetricsNotification} */
const payload = harden({
numVaults: state.prioritizedVaults.getCount(),
totalCollateral: state.totalCollateral,
totalDebt: state.totalDebt,
numLiquidationsCompleted: state.numLiquidationsCompleted,
totalCollateralSold: state.totalCollateralSold,
totalOverageReceived: state.totalOverageReceived,
totalProceedsReceived: state.totalProceedsReceived,
totalShortfallReceived: state.totalShortfallReceived,
});
state.metricsPublication.updateState(payload);
},
/**
* When any Vault's debt ratio is higher than the current high-water level,
* call `reschedulePriceCheck()` to request a fresh notification from the
* priceAuthority. There will be extra outstanding requests since we can't
* cancel them. (https://github.com/Agoric/agoric-sdk/issues/2713).
*
* When the vault with the current highest debt ratio is removed or reduces
* its ratio, we won't reschedule the priceAuthority requests to reduce churn.
* Instead, when a priceQuote is received, we'll only reschedule if the
* high-water level when the request was made matches the current high-water
* level.
*
* @param {MethodContext} context
* @param {Ratio} [highestRatio]
* @returns {Promise<void>}
*/
reschedulePriceCheck: async ({ state, facets }, highestRatio) => {
trace('reschedulePriceCheck', { liquidationQueueing });
// INTERLOCK: the first time through, start the activity to wait for
// and process liquidations over time.
if (!liquidationQueueing) {
liquidationQueueing = true;
// eslint-disable-next-line consistent-return
return facets.helper
.processLiquidations()
.catch(e => console.error('Liquidator failed', e))
.finally(() => {
liquidationQueueing = false;
});
}
if (!outstandingQuote) {
// the new threshold will be picked up by the next quote request
return;
}
const { prioritizedVaults } = state;
const highestDebtRatio = highestRatio || prioritizedVaults.highestRatio();
if (!highestDebtRatio) {
// if there aren't any open vaults, we don't need an outstanding RFQ.
trace('no open vaults');
return;
}
// There is already an activity processing liquidations. It may be
// waiting for the oracle price to cross a threshold.
// Update the current in-progress quote.
const govParams = state.factoryPowers.getGovernedParams();
const liquidationMargin = govParams.getLiquidationMargin();
// Safe to call extraneously (lightweight and idempotent)
E(outstandingQuote).updateLevel(
highestDebtRatio.denominator, // collateral
liquidationThreshold(highestDebtRatio, liquidationMargin),
);
trace('update quote', highestDebtRatio);
},
/**
* @param {MethodContext} context
*/
processLiquidations: async ({ state, facets }) => {
const { prioritizedVaults, priceAuthority } = state;
const govParams = state.factoryPowers.getGovernedParams();
async function* eventualLiquidations() {
while (true) {
const highestDebtRatio = prioritizedVaults.highestRatio();
if (!highestDebtRatio) {
return;
}
const liquidationMargin = govParams.getLiquidationMargin();
// ask to be alerted when the price level falls enough that the vault
// with the highest debt to collateral ratio will no longer be valued at the
// liquidationMargin above its debt.
outstandingQuote = E(priceAuthority).mutableQuoteWhenLT(
highestDebtRatio.denominator, // collateral
liquidationThreshold(highestDebtRatio, liquidationMargin),
);
trace('posted quote request', highestDebtRatio);
// The rest of this method will not happen until after a quote is received.
// This may not happen until much later, when the market changes.
// eslint-disable-next-line no-await-in-loop
const quote = await E(outstandingQuote).getPromise();
outstandingQuote = null;
// When we receive a quote, we check whether the vault with the highest
// ratio of debt to collateral is below the liquidationMargin, and if so,
// we liquidate it. We use ceilDivide to round up because ratios above
// this will be liquidated.
const quoteRatioPlusMargin = makeRatioFromAmounts(
ceilDivideBy(getAmountOut(quote), liquidationMargin),
getAmountIn(quote),
);
trace('quote', quote, quoteRatioPlusMargin);
// Liquidate the head of the queue
const [next] =
prioritizedVaults.entriesPrioritizedGTE(quoteRatioPlusMargin);
if (next) {
yield next;
}
}
}
for await (const next of eventualLiquidations()) {
await facets.helper.liquidateAndRemove(next);
trace('price check liq', next && next[0]);
}
},
/**
* @param {MethodContext} context
* @param {[key: string, vaultKit: Vault]} record
*/
liquidateAndRemove: ({ state, facets }, [key, vault]) => {
const { factoryPowers, prioritizedVaults, zcf } = state;
const vaultSeat = vault.getVaultSeat();
trace('liquidating', vaultSeat.getProposal());
const collateralPre = vault.getCollateralAmount();
// Start liquidation (vaultState: LIQUIDATING)
const liquidator = state.liquidator;
assert(liquidator);
return liquidate(
zcf,
vault,
liquidator,
state.collateralBrand,
factoryPowers.getGovernedParams().getLiquidationPenalty(),
)
.then(accounting => {
facets.manager.burnAndRecord(accounting.runToBurn, vaultSeat);
// current values
state.totalCollateral = AmountMath.subtract(
state.totalCollateral,
collateralPre,
);
state.totalDebt = AmountMath.subtract(
state.totalDebt,
accounting.shortfall,
);
// cumulative values
state.totalProceedsReceived = AmountMath.add(
state.totalProceedsReceived,
accounting.proceeds,
);
state.totalOverageReceived = AmountMath.add(
state.totalOverageReceived,
accounting.overage,
);
state.totalShortfallReceived = AmountMath.add(
state.totalShortfallReceived,
accounting.shortfall,
);
prioritizedVaults.removeVault(key);
trace('liquidated');
state.numLiquidationsCompleted += 1;
facets.helper.updateMetrics();
if (!AmountMath.isEmpty(accounting.shortfall)) {
E(factoryPowers.getShortfallReporter())
.increaseLiquidationShortfall(accounting.shortfall)
.catch(reason =>
console.error(
'liquidateAndRemove failed to increaseLiquidationShortfall',
reason,
),
);
}
})
.catch(e => {
// XXX should notify interested parties
console.error('liquidateAndRemove failed with', e);
throw e;
});
},
};
const managerBehavior = {
/** @param {MethodContext} context */
getGovernedParams: ({ state }) => state.factoryPowers.getGovernedParams(),
/**
* @param {MethodContext} context
* @param {Amount<'nat'>} collateralAmount
*/
maxDebtFor: async ({ state }, collateralAmount) => {
const { debtBrand, priceAuthority } = state;
const quoteAmount = await E(priceAuthority).quoteGiven(
collateralAmount,
debtBrand,
);
// floorDivide because we want the debt ceiling lower
return floorDivideBy(
getAmountOut(quoteAmount),
state.factoryPowers.getGovernedParams().getLiquidationMargin(),
);
},
/**
* TODO utility method to turn a callback into non-actual one
* was type {MintAndReallocate}
*
* @param {MethodContext} context
* @param {Amount} toMint
* @param {Amount} fee
* @param {ZCFSeat} seat
* @param {...ZCFSeat} otherSeats
* @returns {void}
*/
mintAndReallocate: ({ state }, toMint, fee, seat, ...otherSeats) => {
const { factoryPowers, totalDebt } = state;
checkDebtLimit(
factoryPowers.getGovernedParams().getDebtLimit(),
totalDebt,
toMint,
);
state.factoryPowers.mintAndReallocate(toMint, fee, seat, ...otherSeats);
state.totalDebt = AmountMath.add(state.totalDebt, toMint);
},
/**
* @param {MethodContext} context
* @param {Amount<'nat'>} toBurn
* @param {ZCFSeat} seat
*/
burnAndRecord: ({ state }, toBurn, seat) => {
trace('burnAndRecord', { toBurn, totalDebt: state.totalDebt });
const { burnDebt } = state.factoryPowers;
burnDebt(toBurn, seat);
state.totalDebt = AmountMath.subtract(state.totalDebt, toBurn);
},
/** @param {MethodContext} context */
getAssetSubscriber: ({ state }) => state.assetSubscriber,
/** @param {MethodContext} context */
getCollateralBrand: ({ state }) => state.collateralBrand,
/** @param {MethodContext} context */
getDebtBrand: ({ state }) => state.debtBrand,
/**
* coefficient on existing debt to calculate new debt
*
* @param {MethodContext} context
*/
getCompoundedInterest: ({ state }) => state.compoundedInterest,
/**
* Called by a vault when its balances change.
*
* @param {MethodContext} context
* @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
*/
handleBalanceChange: (
{ state, facets },
oldDebtNormalized,
oldCollateral,
vaultId,
vaultPhase,
vault,
) => {
const { prioritizedVaults } = state;
// 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;
if (settled) {
assert(
!prioritizedVaults.hasVaultByAttributes(
oldDebtNormalized,
oldCollateral,
vaultId,
),
'Settled vaults must not be retained in storage',
);
} else {
const isNew = AmountMath.isEmpty(oldDebtNormalized);
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',
);
}
// replace in queue, but only if it can accrue interest or be liquidated (i.e. has debt).
// getCurrentDebt() would also work (0x = 0) but require more computation.
if (!AmountMath.isEmpty(vault.getNormalizedDebt())) {
prioritizedVaults.addVault(vaultId, vault);
}
// totalCollateral += vault's collateral delta (post — pre)
state.totalCollateral = AmountMath.subtract(
AmountMath.add(state.totalCollateral, vault.getCollateralAmount()),
oldCollateral,
);
// debt accounting managed through minting and burning
facets.helper.updateMetrics();
}
},
};
const collateralBehavior = {
/** @param {MethodContext} context */
makeVaultInvitation: ({ state: { zcf }, facets: { self } }) =>
zcf.makeInvitation(self.makeVaultKit, 'MakeVault'),
/** @param {MethodContext} context */
getSubscriber: ({ state }) => state.assetSubscriber,
/** @param {MethodContext} context */
getMetrics: ({ state }) => state.metricsSubscription,
/** @param {MethodContext} context */
getCompoundedInterest: ({ state }) => state.compoundedInterest,
};
const selfBehavior = {
/** @param {MethodContext} context */
getGovernedParams: ({ state }) => state.factoryPowers.getGovernedParams(),
/**
* In extreme situations, system health may require liquidating all vaults.
* This starts the liquidations all in parallel.
*
* @param {MethodContext} context
*/
liquidateAll: async ({ state, facets: { helper } }) => {
const { prioritizedVaults } = state;
const toLiquidate = Array.from(prioritizedVaults.entries()).map(
helper.liquidateAndRemove,
);
await Promise.all(toLiquidate);
},
/**
* @param {MethodContext} context
* @param {ZCFSeat} seat
*/
makeVaultKit: async ({ state, facets: { manager } }, seat) => {
const { prioritizedVaults, zcf } = state;
assertProposalShape(seat, {
give: { Collateral: null },
want: { RUN: null },
});
state.vaultCounter += 1;
const vaultId = String(state.vaultCounter);
const vault = makeVault(zcf, manager, vaultId);
try {
// TODO `await` is allowed until the above ordering is fixed
// eslint-disable-next-line @jessie.js/no-nested-await
const vaultKit = await vault.initVaultKit(seat);
// initVaultKit calls back to handleBalanceChange() which will add the
// vault to prioritizedVaults
seat.exit();
return vaultKit;
} catch (err) {
// ??? do we still need this cleanup? it won't get into the store unless it has collateral,
// which should qualify it to be in the store. If we drop this catch then the nested await
// for `vault.initVaultKit()` goes away.
// remove it from the store if it got in
/** @type {NormalizedDebt} */
// @ts-expect-error cast
const normalizedDebt = AmountMath.makeEmpty(state.debtBrand);
const collateralPre = seat.getCurrentAllocation().Collateral;
try {
prioritizedVaults.removeVaultByAttributes(
normalizedDebt,
collateralPre,
vaultId,
);
console.error('removed vault', vaultId, 'after initVaultKit failure');
} catch {
console.error(
'vault',
vaultId,
'never stored during initVaultKit failure',
);
}
throw err;
}
},
/**
*
* @param {MethodContext} param
* @param {Installation} liquidationInstall
* @param {object} liquidationTerms
*/
setupLiquidator: async (
{ state, facets },
liquidationInstall,
liquidationTerms,
) => {
const { zcf, debtBrand, collateralBrand } = state;
const { ammPublicFacet, priceAuthority, reservePublicFacet, timerService } =
zcf.getTerms();
const zoe = zcf.getZoeService();
const collateralIssuer = zcf.getIssuerForBrand(collateralBrand);
const debtIssuer = zcf.getIssuerForBrand(debtBrand);
trace('setup liquidator', {
debtBrand,
debtIssuer,
collateralBrand,
liquidationTerms,
});
const { creatorFacet, instance } = await E(zoe).startInstance(
liquidationInstall,
harden({ RUN: debtIssuer, Collateral: collateralIssuer }),
harden({
...liquidationTerms,
amm: ammPublicFacet,
debtBrand,
reservePublicFacet,
priceAuthority,
timerService,
}),
);
trace('setup liquidator complete', {
instance,
old: state.liquidatorInstance,
equal: state.liquidatorInstance === instance,
});
state.liquidatorInstance = instance;
state.liquidator = creatorFacet;
facets.helper.assetNotify();
},
/** @param {MethodContext} context */
getCollateralQuote: async ({ state }) => {
const { debtBrand } = state;
// get a quote for one unit of the collateral
const displayInfo = await E(state.collateralBrand).getDisplayInfo();
const decimalPlaces = displayInfo.decimalPlaces || 0n;
return E(state.priceAuthority).quoteGiven(
AmountMath.make(state.collateralBrand, 10n ** Nat(decimalPlaces)),
debtBrand,
);
},
/** @param {MethodContext} context */
getPublicFacet: ({ facets }) => facets.collateral,
};
/** @param {MethodContext} context */
const finish = ({ state, facets: { helper } }) => {
state.prioritizedVaults.onHigherHighest(helper.reschedulePriceCheck);
// push initial state of metrics
helper.updateMetrics();
void observeNotifier(state.periodNotifier, {
updateState: updateTime =>
helper
.chargeAllVaults(updateTime, state.poolIncrementSeat)
.catch(e =>
console.error('🚨 vaultManager failed to charge interest', e),
),
fail: reason => {
state.zcf.shutdownWithFailure(
assert.error(X`Unable to continue without a timer: ${reason}`),
);
},
finish: done => {
state.zcf.shutdownWithFailure(
assert.error(X`Unable to continue without a timer: ${done}`),
);
},
});
};
const behavior = {
collateral: collateralBehavior,
helper: helperBehavior,
manager: managerBehavior,
self: selfBehavior,
};
const makeVaultManagerKit = defineKindMulti(
'VaultManagerKit',
initState,
behavior,
{
finish,
},
);
/**
* Each VaultManager manages a single collateral type.
*
* It manages some number of outstanding loans, each called a Vault, for which
* the collateral is provided in exchange for borrowed RUN.
*
* @param {ZCF} zcf
* @param {ZCFMint<'nat'>} debtMint
* @param {Brand} collateralBrand
* @param {ERef<PriceAuthority>} priceAuthority
* @param {import('./vaultDirector.js').FactoryPowersFacet} factoryPowers
* @param {ERef<TimerService>} timerService
* @param {Timestamp} startTimeStamp
*/
export const makeVaultManager = pickFacet(makeVaultManagerKit, 'self');
/** @typedef {ReturnType<typeof makeVaultManagerKit>['manager']} VaultKitManager */
/** @typedef {ReturnType<typeof makeVaultManager>} VaultManager */
/** @typedef {ReturnType<VaultManager['getPublicFacet']>} CollateralManager */