-
Notifications
You must be signed in to change notification settings - Fork 221
/
Copy pathsmartWallet.js
566 lines (530 loc) · 18.7 KB
/
smartWallet.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
import {
AmountMath,
AmountShape,
BrandShape,
DisplayInfoShape,
IssuerShape,
PaymentShape,
PurseShape,
} from '@agoric/ertp';
import {
observeNotifier,
pipeTopicToStorage,
prepareDurablePublishKit,
SubscriberShape,
TopicsRecordShape,
} from '@agoric/notifier';
import { StorageNodeShape } from '@agoric/notifier/src/typeGuards.js';
import { M, mustMatch } from '@agoric/store';
import { makeScalarBigMapStore, prepareExoClassKit } from '@agoric/vat-data';
import { makeStorageNodePathProvider } from '@agoric/zoe/src/contractSupport/durability.js';
import { E } from '@endo/far';
import { makeInvitationsHelper } from './invitations.js';
import { makeOfferExecutor } from './offers.js';
import { shape } from './typeGuards.js';
import { objectMapStoragePath } from './utils.js';
const { Fail, quote: q } = assert;
const ERROR_LAST_OFFER_ID = -1;
/**
* @template K, V
* @param {MapStore<K, V> } map
* @returns {Record<K, V>}
*/
const mapToRecord = map => Object.fromEntries(map.entries());
/**
* @file Smart wallet module
*
* @see {@link ../README.md}}
*/
// One method yet but structured to support more. For example,
// maybe suggestIssuer for https://github.com/Agoric/agoric-sdk/issues/6132
// setting petnames and adding brands for https://github.com/Agoric/agoric-sdk/issues/6126
/**
* @typedef {{
* method: 'executeOffer'
* offer: import('./offers.js').OfferSpec,
* }} BridgeAction
*/
/**
* Purses is an array to support a future requirement of multiple purses per brand.
*
* @typedef {{
* purses: Array<{brand: Brand, balance: Amount}>,
* offerToUsedInvitation: { [offerId: string]: Amount },
* offerToPublicSubscriberPaths: { [offerId: string]: { [subscriberName: string]: string } },
* lastOfferId: string,
* }} CurrentWalletRecord
*/
/**
* @typedef {{ updated: 'offerStatus', status: import('./offers.js').OfferStatus } |
* { updated: 'balance'; currentAmount: Amount }
* } UpdateRecord Record of an update to the state of this wallet.
*
* Client is responsible for coalescing updates into a current state. See `coalesceUpdates` utility.
*
* The reason for this burden on the client is that publishing
* the full history of offers with each change is untenable.
*/
/**
* @typedef {{
* brand: Brand,
* displayInfo: DisplayInfo,
* issuer: Issuer,
* petname: import('./types').Petname
* }} BrandDescriptor
* For use by clients to describe brands to users. Includes `displayInfo` to save a remote call.
*/
// imports
/** @typedef {import('./types').RemotePurse} RemotePurse */
/**
* @typedef {{
* address: string,
* bank: ERef<import('@agoric/vats/src/vat-bank').Bank>,
* currentStorageNode: StorageNode,
* invitationPurse: Purse<'set'>,
* walletStorageNode: StorageNode,
* }} UniqueParams
*
* @typedef {Pick<MapStore<Brand, BrandDescriptor>, 'has' | 'get' | 'values'>} ReadOnlyMapStore
* @typedef {{
* agoricNames: ERef<import('@agoric/vats').NameHub>,
* registry: ReadOnlyMapStore,
* invitationIssuer: Issuer<'set'>,
* invitationBrand: Brand<'set'>,
* invitationDisplayInfo: DisplayInfo,
* publicMarshaller: Marshaller,
* zoe: ERef<ZoeService>,
* }} SharedParams
*
* @typedef {ImmutableState & MutableState} State
* - `brandPurses` is precious and closely held. defined as late as possible to reduce its scope.
* - `offerToInvitationMakers` is precious and closely held.
* - `offerToPublicSubscriberPaths` is precious and closely held.
* - `purseBalances` is a cache of what we've received from purses. Held so we can publish all balances on change.
*
* @typedef {Readonly<UniqueParams & {
* paymentQueues: MapStore<Brand, Array<import('@endo/far').FarRef<Payment>>>,
* offerToInvitationMakers: MapStore<string, import('./types').RemoteInvitationMakers>,
* offerToPublicSubscriberPaths: MapStore<string, Record<string, string>>,
* offerToUsedInvitation: MapStore<string, Amount>,
* purseBalances: MapStore<RemotePurse, Amount>,
* updatePublishKit: PublishKit<UpdateRecord>,
* currentPublishKit: PublishKit<CurrentWalletRecord>,
* }>} ImmutableState
*
* @typedef {{
* }} MutableState
*/
/**
*
* @param {import('@agoric/vat-data').Baggage} baggage
* @param {SharedParams} shared
*/
export const prepareSmartWallet = (baggage, shared) => {
mustMatch(
shared,
harden({
agoricNames: M.eref(M.remotable('agoricNames')),
invitationIssuer: IssuerShape,
invitationBrand: BrandShape,
invitationDisplayInfo: DisplayInfoShape,
publicMarshaller: M.remotable('Marshaller'),
zoe: M.eref(M.remotable('ZoeService')),
registry: M.remotable('AssetRegistry'), // XXX too strict
}),
);
const makeWalletPublishKit = prepareDurablePublishKit(
baggage,
'Smart Wallet publish kit',
);
const memoizedPath = makeStorageNodePathProvider(baggage);
/**
*
* @param {UniqueParams} unique
* @returns {State}
*/
const initState = unique => {
// Some validation of inputs.
mustMatch(
unique,
harden({
address: M.string(),
bank: M.eref(M.remotable()),
invitationPurse: PurseShape,
currentStorageNode: M.eref(StorageNodeShape),
walletStorageNode: M.eref(StorageNodeShape),
}),
);
const preciousState = {
// Payments that couldn't be deposited when received.
// NB: vulnerable to uncapped growth by unpermissioned deposits.
paymentQueues: makeScalarBigMapStore('payments queues', {
durable: true,
}),
// Invitation amounts to save for persistent lookup
offerToUsedInvitation: makeScalarBigMapStore(
'invitation amounts by offer',
{
durable: true,
},
),
// Invitation makers yielded by offer results
offerToInvitationMakers: makeScalarBigMapStore(
'invitation makers by offer',
{
durable: true,
},
),
// Public subscribers yielded by offer results
offerToPublicSubscriberPaths: makeScalarBigMapStore(
'public subscribers by offer',
{
durable: true,
},
),
};
/** @type {PublishKit<UpdateRecord>} */
const updatePublishKit = makeWalletPublishKit();
// NB: state size must not grow monotonically
// This is the node that UIs subscribe to for everything they need.
// e.g. agoric follow :published.wallet.agoric1nqxg4pye30n3trct0hf7dclcwfxz8au84hr3ht
/** @type {PublishKit<CurrentWalletRecord>} */
const currentPublishKit = makeWalletPublishKit();
const { currentStorageNode, walletStorageNode } = unique;
// Start the publishing loops
pipeTopicToStorage(
updatePublishKit.subscriber,
walletStorageNode,
shared.publicMarshaller,
);
pipeTopicToStorage(
currentPublishKit.subscriber,
currentStorageNode,
shared.publicMarshaller,
);
const nonpreciousState = {
// What purses have reported on construction and by getCurrentAmountNotifier updates.
purseBalances: makeScalarBigMapStore('purse balances', { durable: true }),
/** @type {PublishKit<UpdateRecord>} */
updatePublishKit,
/** @type {PublishKit<CurrentWalletRecord>} */
currentPublishKit,
walletStorageNode,
};
return {
...unique,
...nonpreciousState,
...preciousState,
};
};
const behaviorGuards = {
helper: M.interface('helperFacetI', {
updateBalance: M.call(PurseShape, AmountShape).optional('init').returns(),
publishCurrentState: M.call().returns(),
watchPurse: M.call(M.eref(PurseShape)).returns(M.promise()),
}),
deposit: M.interface('depositFacetI', {
receive: M.callWhen(M.await(M.eref(PaymentShape))).returns(AmountShape),
}),
offers: M.interface('offers facet', {
executeOffer: M.call(shape.OfferSpec).returns(M.promise()),
getLastOfferId: M.call().returns(M.number()),
}),
self: M.interface('selfFacetI', {
handleBridgeAction: M.call(shape.StringCapData, M.boolean()).returns(
M.promise(),
),
getDepositFacet: M.call().returns(M.remotable()),
getOffersFacet: M.call().returns(M.remotable()),
getCurrentSubscriber: M.call().returns(SubscriberShape),
getUpdatesSubscriber: M.call().returns(SubscriberShape),
getPublicTopics: M.call().returns(TopicsRecordShape),
}),
};
/**
* Make the durable object to return, but taking some parameters that are awaited by a wrapping function.
* This is necessary because the class kit construction helpers, `initState` and `finish` run synchronously
* and the child storage node must be awaited until we have durable promises.
*/
const makeWalletWithResolvedStorageNodes = prepareExoClassKit(
baggage,
'SmartWallet',
behaviorGuards,
initState,
{
helper: {
/**
* @param {RemotePurse} purse
* @param {Amount<any>} balance
* @param {'init'} [init]
*/
updateBalance(purse, balance, init) {
const { purseBalances, updatePublishKit } = this.state;
if (init) {
purseBalances.init(purse, balance);
} else {
purseBalances.set(purse, balance);
}
updatePublishKit.publisher.publish({
updated: 'balance',
currentAmount: balance,
});
const { helper } = this.facets;
helper.publishCurrentState();
},
publishCurrentState() {
const {
currentPublishKit,
offerToUsedInvitation,
offerToPublicSubscriberPaths,
purseBalances,
} = this.state;
currentPublishKit.publisher.publish({
purses: [...purseBalances.values()].map(a => ({
brand: a.brand,
balance: a,
})),
offerToUsedInvitation: mapToRecord(offerToUsedInvitation),
offerToPublicSubscriberPaths: mapToRecord(
offerToPublicSubscriberPaths,
),
// @ts-expect-error FIXME leftover from offer id string conversion
lastOfferId: ERROR_LAST_OFFER_ID,
});
},
/** @type {(purse: ERef<RemotePurse>) => Promise<void>} */
async watchPurse(purseRef) {
const { address } = this.state;
const purse = await purseRef; // promises don't fit in durable storage
const { helper } = this.facets;
// publish purse's balance and changes
void E.when(
E(purse).getCurrentAmount(),
balance => helper.updateBalance(purse, balance, 'init'),
err =>
console.error(
address,
'initial purse balance publish failed',
err,
),
);
void observeNotifier(E(purse).getCurrentAmountNotifier(), {
updateState(balance) {
helper.updateBalance(purse, balance);
},
fail(reason) {
console.error(address, `failed updateState observer`, reason);
},
});
},
},
/**
* Similar to {DepositFacet} but async because it has to look up the purse.
*/
deposit: {
/**
* Put the assets from the payment into the appropriate purse.
*
* If the purse doesn't exist, we hold the payment until it does.
*
* @param {import('@endo/far').FarRef<Payment>} payment
* @returns {Promise<Amount>} amounts for deferred deposits will be empty
*/
async receive(payment) {
const { paymentQueues: queues, bank, invitationPurse } = this.state;
const { registry, invitationBrand } = shared;
const brand = await E(payment).getAllegedBrand();
// When there is a purse deposit into it
if (registry.has(brand)) {
const purse = E(bank).getPurse(brand);
// @ts-expect-error deposit does take a FarRef<Payment>
return E(purse).deposit(payment);
} else if (invitationBrand === brand) {
// @ts-expect-error deposit does take a FarRef<Payment>
return E(invitationPurse).deposit(payment);
}
// When there is no purse, queue the payment
if (queues.has(brand)) {
queues.get(brand).push(payment);
} else {
queues.init(brand, harden([payment])); // @@ this can't be right
}
return AmountMath.makeEmpty(brand);
},
},
offers: {
/**
* @deprecated
* @returns {number} an error code, for backwards compatibility with clients expecting a number
*/
getLastOfferId() {
return ERROR_LAST_OFFER_ID;
},
/**
* Take an offer description provided in capData, augment it with payments and call zoe.offer()
*
* @param {import('./offers.js').OfferSpec} offerSpec
* @returns {Promise<void>} when the offer has been sent to Zoe; payouts go into this wallet's purses
* @throws if any parts of the offer can be determined synchronously to be invalid
*/
async executeOffer(offerSpec) {
const { facets } = this;
const {
address,
bank,
invitationPurse,
offerToInvitationMakers,
offerToUsedInvitation,
offerToPublicSubscriberPaths,
updatePublishKit,
} = this.state;
const { invitationBrand, zoe, invitationIssuer, registry } = shared;
const logger = {
info: (...args) => console.info('wallet', address, ...args),
error: (...args) => console.log('wallet', address, ...args),
};
const executor = makeOfferExecutor({
zoe,
depositFacet: facets.deposit,
invitationIssuer,
powers: {
invitationFromSpec: makeInvitationsHelper(
zoe,
invitationBrand,
invitationPurse,
offerToInvitationMakers.get,
),
/**
* @param {Brand} brand
* @returns {Promise<RemotePurse>}
*/
purseForBrand: async brand => {
if (registry.has(brand)) {
// @ts-expect-error RemotePurse cast
return E(bank).getPurse(brand);
} else if (invitationBrand === brand) {
// @ts-expect-error RemotePurse cast
return invitationPurse;
}
throw assert.error(`cannot find/make purse for ${brand}`);
},
logger,
},
onStatusChange: offerStatus => {
logger.info('offerStatus', offerStatus);
updatePublishKit.publisher.publish({
updated: 'offerStatus',
status: offerStatus,
});
},
/** @type {(offerId: string, invitationAmount: Amount<'set'>, invitationMakers: import('./types').RemoteInvitationMakers, publicSubscribers?: import('./types').PublicSubscribers | import('@agoric/notifier').TopicsRecord) => Promise<void>} */
onNewContinuingOffer: async (
offerId,
invitationAmount,
invitationMakers,
publicSubscribers,
) => {
offerToUsedInvitation.init(offerId, invitationAmount);
offerToInvitationMakers.init(offerId, invitationMakers);
const pathMap = await objectMapStoragePath(publicSubscribers);
if (pathMap) {
logger.info('recording pathMap', pathMap);
offerToPublicSubscriberPaths.init(offerId, pathMap);
}
facets.helper.publishCurrentState();
},
});
await executor.executeOffer(offerSpec);
},
},
self: {
/**
*
* @param {import('@endo/marshal').CapData<string>} actionCapData of type BridgeAction
* @param {boolean} [canSpend=false]
* @returns {Promise<void>}
*/
handleBridgeAction(actionCapData, canSpend = false) {
const { publicMarshaller } = shared;
const { offers } = this.facets;
return E.when(
E(publicMarshaller).unserialize(actionCapData),
/** @param {BridgeAction} action */
action => {
switch (action.method) {
case 'executeOffer': {
assert(canSpend, 'executeOffer requires spend authority');
return offers.executeOffer(action.offer);
}
default: {
throw Fail`invalid handle bridge action ${q(action)}`;
}
}
},
);
},
getDepositFacet() {
return this.facets.deposit;
},
getOffersFacet() {
return this.facets.offers;
},
/** @deprecated use getPublicTopics */
getCurrentSubscriber() {
return this.state.currentPublishKit.subscriber;
},
/** @deprecated use getPublicTopics */
getUpdatesSubscriber() {
return this.state.updatePublishKit.subscriber;
},
getPublicTopics() {
const {
currentPublishKit,
currentStorageNode,
updatePublishKit,
walletStorageNode,
} = this.state;
return harden({
current: {
description: 'Current state of wallet',
subscriber: currentPublishKit.subscriber,
storagePath: memoizedPath(currentStorageNode),
},
updates: {
description: 'Changes to wallet',
subscriber: updatePublishKit.subscriber,
storagePath: memoizedPath(walletStorageNode),
},
});
},
},
},
{
finish: async ({ state, facets }) => {
const { invitationPurse } = state;
const { helper } = facets;
// @ts-expect-error RemotePurse cast
helper.watchPurse(invitationPurse);
},
},
);
/**
* @param {Omit<UniqueParams, 'currentStorageNode' | 'walletStorageNode'> & {walletStorageNode: ERef<StorageNode>}} uniqueWithoutChildNodes
*/
const makeSmartWallet = async uniqueWithoutChildNodes => {
const [walletStorageNode, currentStorageNode] = await Promise.all([
uniqueWithoutChildNodes.walletStorageNode,
E(uniqueWithoutChildNodes.walletStorageNode).makeChildNode('current'),
]);
return makeWalletWithResolvedStorageNodes(
harden({
...uniqueWithoutChildNodes,
currentStorageNode,
walletStorageNode,
}),
).self;
};
return makeSmartWallet;
};
harden(prepareSmartWallet);
/** @typedef {Awaited<ReturnType<ReturnType<typeof prepareSmartWallet>>>} SmartWallet */