@agoric/vats 0.15.2-dev-3294e0c.0.3294e0c → 0.15.2-dev-488dec7.0.488dec7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,543 @@
1
+ // @ts-check
2
+ import { Fail, X, q } from '@endo/errors';
3
+ import { E } from '@endo/far';
4
+
5
+ import { AmountMath } from '@agoric/ertp';
6
+ import { deeplyFulfilledObject, makeTracer } from '@agoric/internal';
7
+ import { UnguardedHelperI } from '@agoric/internal/src/typeGuards.js';
8
+ import { isUpgradeDisconnection } from '@agoric/internal/src/upgrade-api.js';
9
+ import {
10
+ observeIteration,
11
+ observeNotifier,
12
+ subscribeEach,
13
+ } from '@agoric/notifier';
14
+ import { makeAtomicProvider, makeScalarMapStore } from '@agoric/store';
15
+ import { M, makeScalarBigSetStore } from '@agoric/vat-data';
16
+ import {
17
+ PublicTopicShape,
18
+ makeRecorderTopic,
19
+ } from '@agoric/zoe/src/contractSupport/topics.js';
20
+ import { PowerFlags } from './walletFlags.js';
21
+
22
+ /**
23
+ * @import {EReturn} from '@endo/far';
24
+ * @import {BridgeMessage} from '@agoric/cosmic-swingset/src/types.js';
25
+ * @import {Amount, Brand, Payment, Purse} from '@agoric/ertp';
26
+ * @import {ERemote, Remote} from '@agoric/internal';
27
+ * @import {StorageNode} from '@agoric/internal/src/lib-chainStorage.js';
28
+ * @import {ZCF} from '@agoric/zoe';
29
+ * @import {ERef} from '@endo/far'
30
+ * @import {Bank, BankManager} from '@agoric/vats/src/vat-bank.js'
31
+ * @import {MapStore, SetStore} from '@agoric/store';
32
+ * @import {NameAdmin} from '@agoric/vats';
33
+ * @import {WalletFactoryStartResult} from '@agoric/vats/src/core/startWalletFactory.js';
34
+ * @import {Zone} from '@agoric/zone';
35
+ * @import {start as StartWalletFactory} from '@agoric/smart-wallet/src/walletFactory.js';
36
+ * @import {MakeRecorderKit} from '@agoric/zoe/src/contractSupport/recorder.js';
37
+ * @import {RecorderKit} from '@agoric/zoe/src/contractSupport/recorder.js';
38
+ * @import {BridgeHandler} from '@agoric/vats';
39
+ * @import {AssetDescriptor} from '@agoric/vats/src/vat-bank.js';
40
+ */
41
+
42
+ const trace = makeTracer('ProvPool');
43
+
44
+ const FIRST_UPPER_KEYWORD = /^[A-Z][a-zA-Z0-9_$]*$/;
45
+ // see https://github.com/Agoric/agoric-sdk/issues/8238
46
+ const FIRST_LOWER_NEAR_KEYWORD = /^[a-z][a-zA-Z0-9_$]*$/;
47
+
48
+ // XXX when inferred, error TS2742: cannot be named without a reference to '../../../node_modules/@endo/exo/src/get-interface.js'. This is likely not portable. A type annotation is necessary.
49
+ /**
50
+ * @typedef {{
51
+ * machine: {
52
+ * addRevivableAddresses: (oldAddresses: string[]) => void;
53
+ * getWalletReviver: () => ERef<any>;
54
+ * setReferences: (erefs: ProvisionPoolKitReferences) => Promise<void>;
55
+ * makeHandler: () => ERef<BridgeHandler>;
56
+ * };
57
+ * helper: any;
58
+ * forHandler: any;
59
+ * public: any;
60
+ * }} ProvisionPoolKit
61
+ */
62
+
63
+ /**
64
+ * @typedef {object} ProvisionPoolKitReferences
65
+ * @property {ERef<BankManager>} bankManager
66
+ * @property {ERef<NameAdmin>} namesByAddressAdmin
67
+ * @property {ERef<WalletFactoryStartResult['creatorFacet']>} walletFactory
68
+ */
69
+
70
+ /**
71
+ * @typedef {object} MetricsNotification Metrics naming scheme is that nouns are
72
+ * present values and past-participles are accumulative.
73
+ * @property {bigint} walletsProvisioned count of new wallets provisioned
74
+ * @property {Amount<'nat'>} totalMintedProvided running sum of Minted provided
75
+ * to new wallets
76
+ * @property {Amount<'nat'>} totalMintedConverted running sum of Minted ever
77
+ * received by the contract
78
+ */
79
+
80
+ /**
81
+ * Given attenuated access to the funding purse, handle requests to provision
82
+ * smart wallets.
83
+ *
84
+ * @param {Zone} zone
85
+ */
86
+ export const prepareBridgeProvisionTool = zone =>
87
+ zone.exoClass(
88
+ 'smartWalletProvisioningHandler',
89
+ M.interface('ProvisionBridgeHandlerMaker', {
90
+ fromBridge: M.callWhen(M.record()).returns(),
91
+ }),
92
+ /**
93
+ * @param {ERef<BankManager>} bankManager
94
+ * @param {ERef<EReturn<StartWalletFactory>['creatorFacet']>} walletFactory
95
+ * @param {ERef<NameAdmin>} namesByAddressAdmin
96
+ * @param {ProvisionPoolKit['forHandler']} forHandler
97
+ */
98
+ (bankManager, walletFactory, namesByAddressAdmin, forHandler) => ({
99
+ bankManager,
100
+ walletFactory,
101
+ namesByAddressAdmin,
102
+ forHandler,
103
+ }),
104
+ {
105
+ /** @param {BridgeMessage} obj */
106
+ async fromBridge(obj) {
107
+ if (obj.type !== 'PLEASE_PROVISION')
108
+ throw Fail`Unrecognized request ${obj.type}`;
109
+ trace('PLEASE_PROVISION', obj);
110
+ const { address, powerFlags } = obj;
111
+ // XXX expects powerFlags to be an array, but if it's a string then
112
+ // this allows a string that has 'SMART_WALLET' in it.
113
+ powerFlags.includes(PowerFlags.SMART_WALLET) ||
114
+ Fail`missing SMART_WALLET in powerFlags`;
115
+
116
+ const { bankManager, walletFactory, namesByAddressAdmin, forHandler } =
117
+ this.state;
118
+
119
+ const bank = E(bankManager).getBankForAddress(address);
120
+ // only proceed if we can provide funds
121
+ await forHandler.sendInitialPayment(bank);
122
+
123
+ const [_, created] = await E(walletFactory).provideSmartWallet(
124
+ address,
125
+ bank,
126
+ namesByAddressAdmin,
127
+ );
128
+ if (created) {
129
+ forHandler.onProvisioned();
130
+ }
131
+ trace(created ? 'provisioned' : 're-provisioned', address);
132
+ },
133
+ },
134
+ );
135
+
136
+ /**
137
+ * @param {Zone} zone
138
+ * @param {{
139
+ * makeRecorderKit: MakeRecorderKit;
140
+ * params: any;
141
+ * poolBank: ERef<Bank>;
142
+ * zcf: ZCF;
143
+ * makeBridgeProvisionTool: ReturnType<typeof prepareBridgeProvisionTool>;
144
+ * }} powers
145
+ */
146
+ export const prepareProvisionPoolKit = (
147
+ zone,
148
+ { makeRecorderKit, params, poolBank, zcf, makeBridgeProvisionTool },
149
+ ) => {
150
+ const ephemeralPurses = makeScalarMapStore('fundingPurseForBrand');
151
+ const purseProvider = makeAtomicProvider(ephemeralPurses);
152
+ const getFundingPurseForBrand = async poolBrand => {
153
+ await null;
154
+ try {
155
+ const purse = await purseProvider.provideAsync(poolBrand, brand =>
156
+ E(poolBank).getPurse(brand),
157
+ );
158
+ return purse;
159
+ } catch (err) {
160
+ trace(`🚨 could not get purse for brand ${poolBrand}`, err);
161
+ throw err;
162
+ }
163
+ };
164
+
165
+ const makeProvisionPoolKitInternal = zone.exoClassKit(
166
+ 'ProvisionPoolKit',
167
+ {
168
+ machine: M.interface('ProvisionPoolKit machine', {
169
+ addRevivableAddresses: M.call(M.arrayOf(M.string())).returns(),
170
+ getWalletReviver: M.call().returns(
171
+ M.remotable('ProvisionPoolKit wallet reviver'),
172
+ ),
173
+ setReferences: M.callWhen({
174
+ bankManager: M.eref(M.remotable('bankManager')),
175
+ namesByAddressAdmin: M.eref(M.remotable('nameAdmin')),
176
+ walletFactory: M.eref(M.remotable('walletFactory')),
177
+ }).returns(),
178
+ makeHandler: M.call().returns(M.remotable('BridgeHandler')),
179
+ }),
180
+ walletReviver: M.interface('ProvisionPoolKit wallet reviver', {
181
+ reviveWallet: M.callWhen(M.string()).returns(
182
+ M.remotable('SmartWallet'),
183
+ ),
184
+ ackWallet: M.call(M.string()).returns(M.boolean()),
185
+ }),
186
+ helper: UnguardedHelperI,
187
+ forHandler: UnguardedHelperI,
188
+ public: M.interface('ProvisionPoolKit public', {
189
+ getPublicTopics: M.call().returns({ metrics: PublicTopicShape }),
190
+ }),
191
+ },
192
+ /**
193
+ * @param {object} opts
194
+ * @param {Purse<'nat'>} [opts.fundPurse]
195
+ * @param {Brand<'nat'>} opts.poolBrand
196
+ * @param {Remote<StorageNode>} opts.metricsNode
197
+ */
198
+ ({ fundPurse, poolBrand, metricsNode }) => {
199
+ /** @type {RecorderKit<MetricsNotification>} */
200
+ const metricsRecorderKit = makeRecorderKit(metricsNode);
201
+
202
+ const revivableAddresses = makeScalarBigSetStore('revivableAddresses', {
203
+ durable: true,
204
+ keyShape: M.string(),
205
+ });
206
+
207
+ /**
208
+ * to be set by `setReferences`
209
+ *
210
+ * @type {Partial<ProvisionPoolKitReferences>}
211
+ */
212
+ const references = {
213
+ bankManager: undefined,
214
+ namesByAddressAdmin: undefined,
215
+ walletFactory: undefined,
216
+ };
217
+
218
+ return {
219
+ fundPurse,
220
+ metricsRecorderKit,
221
+ poolBrand,
222
+ walletsProvisioned: 0n,
223
+ totalMintedProvided: AmountMath.makeEmpty(poolBrand),
224
+ totalMintedConverted: AmountMath.makeEmpty(poolBrand),
225
+ revivableAddresses,
226
+ ...references,
227
+ };
228
+ },
229
+ {
230
+ // aka "limitedCreatorFacet"
231
+ machine: {
232
+ /** @param {string[]} oldAddresses */
233
+ addRevivableAddresses(oldAddresses) {
234
+ trace('revivableAddresses count', oldAddresses.length);
235
+ this.state.revivableAddresses.addAll(oldAddresses);
236
+ },
237
+ getWalletReviver() {
238
+ return this.facets.walletReviver;
239
+ },
240
+ /** @param {ProvisionPoolKitReferences} erefs */
241
+ async setReferences(erefs) {
242
+ const { bankManager, namesByAddressAdmin, walletFactory } = erefs;
243
+ const obj = harden({
244
+ bankManager,
245
+ namesByAddressAdmin,
246
+ walletFactory,
247
+ });
248
+ const refs = await deeplyFulfilledObject(obj);
249
+ Object.assign(this.state, refs);
250
+ },
251
+ /** @returns {BridgeHandler} */
252
+ makeHandler() {
253
+ const { bankManager, namesByAddressAdmin, walletFactory } =
254
+ this.state;
255
+ if (!bankManager || !namesByAddressAdmin || !walletFactory) {
256
+ throw Fail`must set references before handling requests`;
257
+ }
258
+
259
+ const { forHandler } = this.facets;
260
+
261
+ const provisionHandler = makeBridgeProvisionTool(
262
+ bankManager,
263
+ walletFactory,
264
+ namesByAddressAdmin,
265
+ forHandler,
266
+ );
267
+
268
+ return provisionHandler;
269
+ },
270
+ },
271
+ walletReviver: {
272
+ /** @param {string} address */
273
+ async reviveWallet(address) {
274
+ const {
275
+ revivableAddresses,
276
+ bankManager,
277
+ namesByAddressAdmin,
278
+ walletFactory,
279
+ } = this.state;
280
+ if (!bankManager || !namesByAddressAdmin || !walletFactory) {
281
+ throw Fail`must set references before handling requests`;
282
+ }
283
+ revivableAddresses.has(address) ||
284
+ Fail`non-revivable address ${address}`;
285
+ const bank = E(bankManager).getBankForAddress(address);
286
+ const [wallet, _created] = await E(walletFactory).provideSmartWallet(
287
+ address,
288
+ bank,
289
+ namesByAddressAdmin,
290
+ );
291
+ return wallet;
292
+ },
293
+ /**
294
+ * @param {string} address
295
+ * @returns {boolean} isRevive
296
+ */
297
+ ackWallet(address) {
298
+ const { revivableAddresses } = this.state;
299
+ if (!revivableAddresses.has(address)) {
300
+ return false;
301
+ }
302
+ revivableAddresses.delete(address);
303
+ return true;
304
+ },
305
+ },
306
+ helper: {
307
+ publishMetrics() {
308
+ const {
309
+ metricsRecorderKit,
310
+ walletsProvisioned,
311
+ totalMintedConverted,
312
+ totalMintedProvided,
313
+ } = this.state;
314
+ void metricsRecorderKit.recorder.write(
315
+ harden({
316
+ walletsProvisioned,
317
+ totalMintedProvided,
318
+ totalMintedConverted,
319
+ }),
320
+ );
321
+ },
322
+ onTrade(converted) {
323
+ const { state, facets } = this;
324
+ state.totalMintedConverted = AmountMath.add(
325
+ state.totalMintedConverted,
326
+ converted,
327
+ );
328
+ facets.helper.publishMetrics();
329
+ },
330
+ onSendFunds(provided) {
331
+ const { state, facets } = this;
332
+ state.totalMintedProvided = AmountMath.add(
333
+ state.totalMintedProvided,
334
+ provided,
335
+ );
336
+ facets.helper.publishMetrics();
337
+ },
338
+ /**
339
+ * @param {ERef<Purse>} exchangePurse
340
+ * @param {ERef<Brand>} brand
341
+ */
342
+ watchCurrentAmount(exchangePurse, brand) {
343
+ const { helper } = this.facets;
344
+ void observeNotifier(E(exchangePurse).getCurrentAmountNotifier(), {
345
+ updateState: async amount => {
346
+ trace('provisionPool balance update', amount);
347
+ },
348
+ fail: reason => {
349
+ if (isUpgradeDisconnection(reason)) {
350
+ void helper.watchCurrentAmount(exchangePurse, brand);
351
+ } else {
352
+ console.error(reason);
353
+ }
354
+ },
355
+ });
356
+ },
357
+ watchAssetSubscription() {
358
+ const { facets } = this;
359
+ const { helper } = facets;
360
+
361
+ /** @param {AssetDescriptor} desc */
362
+ const repairDesc = desc => {
363
+ if (desc.issuerName.match(FIRST_UPPER_KEYWORD)) {
364
+ trace(`Saving Issuer ${desc.issuerName}`);
365
+ return desc;
366
+ } else if (desc.issuerName.match(FIRST_LOWER_NEAR_KEYWORD)) {
367
+ const bad = desc.issuerName;
368
+ const goodName = bad.replace(bad[0], bad[0].toUpperCase());
369
+
370
+ trace(
371
+ `Saving Issuer ${desc.issuerName} with repaired keyword ${goodName}`,
372
+ );
373
+ return { ...desc, issuerName: goodName };
374
+ } else {
375
+ console.error(
376
+ `unable to save issuer with illegal keyword: ${desc.issuerName}`,
377
+ );
378
+ return undefined;
379
+ }
380
+ };
381
+
382
+ return observeIteration(
383
+ subscribeEach(E(poolBank).getAssetSubscription()),
384
+ {
385
+ updateState: async desc => {
386
+ await null;
387
+ const issuer = zcf.getTerms().issuers[desc.issuerName];
388
+ if (issuer === desc.issuer) {
389
+ trace('provisionPool re-notified of known asset', desc.brand);
390
+ } else {
391
+ const goodDesc = repairDesc(desc);
392
+ if (goodDesc) {
393
+ await zcf.saveIssuer(goodDesc.issuer, goodDesc.issuerName);
394
+ } else {
395
+ console.error(
396
+ `unable to save issuer with illegal keyword: ${desc.issuerName}`,
397
+ );
398
+ }
399
+ }
400
+
401
+ /** @type {ERef<Purse>} */
402
+ const exchangePurse = E(poolBank).getPurse(desc.brand);
403
+ helper.watchCurrentAmount(exchangePurse, desc.brand);
404
+ },
405
+ fail: _reason => {
406
+ void helper.watchAssetSubscription();
407
+ },
408
+ },
409
+ );
410
+ },
411
+ /**
412
+ * @param {Brand<'nat'>} poolBrand
413
+ * @param {object} [options]
414
+ * @param {MetricsNotification} [options.metrics]
415
+ */
416
+ start(poolBrand, { metrics } = {}) {
417
+ const { facets, state } = this;
418
+ const { helper } = facets;
419
+ const lastPoolBrand = state.poolBrand;
420
+
421
+ // The PerAccountInitialAmount param must use the correct brand for
422
+ // this incarnation.
423
+ AmountMath.coerce(poolBrand, params.getPerAccountInitialAmount());
424
+
425
+ // Restore old metrics.
426
+ if (metrics) {
427
+ const {
428
+ walletsProvisioned,
429
+ totalMintedProvided,
430
+ totalMintedConverted,
431
+ } = metrics;
432
+ assert.typeof(walletsProvisioned, 'bigint');
433
+ AmountMath.coerce(lastPoolBrand, totalMintedProvided);
434
+ AmountMath.coerce(lastPoolBrand, totalMintedConverted);
435
+ Object.assign(state, {
436
+ walletsProvisioned,
437
+ totalMintedProvided,
438
+ totalMintedConverted,
439
+ });
440
+ helper.publishMetrics();
441
+ }
442
+
443
+ // Update as needed when `poolBrand` changes.
444
+ if (poolBrand !== lastPoolBrand) {
445
+ state.poolBrand = poolBrand;
446
+ state.fundPurse = undefined;
447
+ void getFundingPurseForBrand(poolBrand).then(purse =>
448
+ helper.updateFundPurse(purse, poolBrand),
449
+ );
450
+ state.totalMintedProvided = AmountMath.makeEmpty(poolBrand);
451
+ state.totalMintedConverted = AmountMath.makeEmpty(poolBrand);
452
+ helper.publishMetrics();
453
+ }
454
+
455
+ void helper.watchAssetSubscription();
456
+ },
457
+ /**
458
+ * @param {Purse<'nat'>} purse
459
+ * @param {Brand<'nat'>} brand
460
+ */
461
+ updateFundPurse(purse, brand) {
462
+ const { state } = this;
463
+ if (brand !== state.poolBrand || state.fundPurse) return;
464
+ state.fundPurse = purse;
465
+ },
466
+ },
467
+ forHandler: {
468
+ onProvisioned() {
469
+ const { facets, state } = this;
470
+ state.walletsProvisioned += 1n;
471
+ facets.helper.publishMetrics();
472
+ },
473
+ /** @param {ERef<Bank>} destBank */
474
+ async sendInitialPayment(destBank) {
475
+ await null;
476
+ const { facets, state } = this;
477
+ const { helper } = facets;
478
+ const {
479
+ poolBrand,
480
+ fundPurse = await getFundingPurseForBrand(poolBrand),
481
+ } = state;
482
+ const perAccountInitialAmount = /** @type {Amount<'nat'>} */ (
483
+ params.getPerAccountInitialAmount()
484
+ );
485
+ trace('sendInitialPayment withdrawing', perAccountInitialAmount);
486
+ const initialPmt = await E(fundPurse).withdraw(
487
+ perAccountInitialAmount,
488
+ );
489
+
490
+ const destPurse = E(destBank).getPurse(poolBrand);
491
+ return E(destPurse)
492
+ .deposit(initialPmt)
493
+ .then(amt => {
494
+ helper.onSendFunds(perAccountInitialAmount);
495
+ trace('provisionPool sent', amt);
496
+ })
497
+ .catch(reason => {
498
+ console.error(X`initial deposit failed: ${q(reason)}`);
499
+ void E(fundPurse).deposit(initialPmt);
500
+ throw reason;
501
+ });
502
+ },
503
+ },
504
+ public: {
505
+ getPublicTopics() {
506
+ return {
507
+ metrics: makeRecorderTopic(
508
+ 'Provision Pool metrics',
509
+ this.state.metricsRecorderKit,
510
+ ),
511
+ };
512
+ },
513
+ },
514
+ },
515
+ {
516
+ finish: ({ facets }) => {
517
+ facets.helper.publishMetrics();
518
+ },
519
+ },
520
+ );
521
+
522
+ /**
523
+ * Prepare synchronous values before passing to real Exo maker
524
+ *
525
+ * @param {object} opts
526
+ * @param {Brand<'nat'>} opts.poolBrand
527
+ * @param {ERemote<StorageNode>} opts.storageNode
528
+ * @returns {Promise<ProvisionPoolKit>}
529
+ */
530
+ const makeProvisionPoolKit = async ({ poolBrand, storageNode }) => {
531
+ const fundPurse = await getFundingPurseForBrand(poolBrand);
532
+ /** @type {Remote<StorageNode>} */
533
+ const metricsNode = await E(storageNode).makeChildNode('metrics');
534
+
535
+ return makeProvisionPoolKitInternal({
536
+ fundPurse,
537
+ poolBrand,
538
+ metricsNode,
539
+ });
540
+ };
541
+
542
+ return makeProvisionPoolKit;
543
+ };