-
Notifications
You must be signed in to change notification settings - Fork 219
/
Copy pathsmartWallet.js
1008 lines (917 loc) · 33.6 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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { E } from '@endo/far';
import {
AmountShape,
BrandShape,
DisplayInfoShape,
IssuerShape,
PaymentShape,
PurseShape,
} from '@agoric/ertp';
import {
deeplyFulfilledObject,
makeTracer,
objectMap,
StorageNodeShape,
} from '@agoric/internal';
import { observeNotifier } from '@agoric/notifier';
import { M, mustMatch } from '@agoric/store';
import {
appendToStoredArray,
provideLazy,
} from '@agoric/store/src/stores/store-utils.js';
import {
makeScalarBigMapStore,
makeScalarBigWeakMapStore,
prepareExoClassKit,
provide,
} from '@agoric/vat-data';
import {
prepareRecorderKit,
SubscriberShape,
TopicsRecordShape,
} from '@agoric/zoe/src/contractSupport/index.js';
import {
AmountKeywordRecordShape,
PaymentPKeywordRecordShape,
} from '@agoric/zoe/src/typeGuards.js';
import { makeInvitationsHelper } from './invitations.js';
import { shape } from './typeGuards.js';
import { objectMapStoragePath } from './utils.js';
import { makeOfferWatcherMaker, watchOfferOutcomes } from './offerWatcher.js';
const { Fail, quote: q } = assert;
const trace = makeTracer('SmrtWlt');
/**
* @file Smart wallet module
*
* @see {@link ../README.md}}
*/
/** @typedef {number | string} OfferId */
/**
* @typedef {{
* id: OfferId,
* invitationSpec: import('./invitations').InvitationSpec,
* proposal: Proposal,
* offerArgs?: unknown
* }} OfferSpec
*/
/**
* @typedef {{
* logger: {info: (...args: any[]) => void, error: (...args: any[]) => void},
* makeOfferWatcher: import('./offerWatcher.js').MakeOfferWatcher,
* invitationFromSpec: import('./invitations.js').InvitationFromSpec,
* }} ExecutorPowers
*/
/**
* @typedef {{
* method: 'executeOffer'
* offer: OfferSpec,
* }} ExecuteOfferAction
*/
/**
* @typedef {{
* method: 'tryExitOffer'
* offerId: OfferId,
* }} TryExitOfferAction
*/
// Discriminated union. Possible future messages types:
// 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 { ExecuteOfferAction | TryExitOfferAction } BridgeAction
*/
/**
* Purses is an array to support a future requirement of multiple purses per brand.
*
* Each map is encoded as an array of entries because a Map doesn't serialize directly.
* We also considered having a vstorage key for each offer but for now are sticking with this design.
*
* Cons
* - Reserializes previously written results when a new result is added
* - Optimizes reads though writes are on-chain (~100 machines) and reads are off-chain (to 1 machine)
*
* Pros
* - Reading all offer results happens much more (>100) often than storing a new offer result
* - Reserialization and writes are paid in execution gas, whereas reads are not
*
* This design should be revisited if ever batch querying across vstorage keys become cheaper or reads be paid.
*
* @typedef {{
* purses: Array<{brand: Brand, balance: Amount}>,
* offerToUsedInvitation: Array<[ offerId: string, usedInvitation: Amount ]>,
* offerToPublicSubscriberPaths: Array<[ offerId: string, publicTopics: { [subscriberName: string]: string } ]>,
* liveOffers: Array<[OfferId, import('./offerWatcher.js').OfferStatus]>,
* }} CurrentWalletRecord
*/
/**
* @typedef {{ updated: 'offerStatus', status: import('./offerWatcher.js').OfferStatus }
* | { updated: 'balance'; currentAmount: Amount }
* | { updated: 'walletAction'; status: { error: string } }
* } 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.
*
* `balance` update supports forward-compatibility for more than one purse per
* brand. An additional key will be needed to disambiguate. For now the brand in
* the amount suffices.
*/
/**
* @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.
*/
/**
* @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'>} BrandDescriptorRegistry
* @typedef {{
* agoricNames: ERef<import('@agoric/vats').NameHub>,
* registry: BrandDescriptorRegistry,
* 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<Payment>>,
* offerToInvitationMakers: MapStore<string, import('./types').InvitationMakers>,
* offerToPublicSubscriberPaths: MapStore<string, Record<string, string>>,
* offerToUsedInvitation: MapStore<string, Amount>,
* purseBalances: MapStore<Purse, Amount>,
* updateRecorderKit: import('@agoric/zoe/src/contractSupport/recorder.js').RecorderKit<UpdateRecord>,
* currentRecorderKit: import('@agoric/zoe/src/contractSupport/recorder.js').RecorderKit<CurrentWalletRecord>,
* liveOffers: MapStore<OfferId, import('./offerWatcher.js').OfferStatus>,
* liveOfferSeats: MapStore<OfferId, UserSeat<unknown>>,
* liveOfferPayments: MapStore<OfferId, MapStore<Brand, Payment>>,
* }>} ImmutableState
*
* @typedef {BrandDescriptor & { purse: Purse }} PurseRecord
* @typedef {{
* }} MutableState
*/
/**
* NameHub reverse-lookup, finding 0 or more names for a target value
*
* TODO: consider moving to nameHub.js?
*
* @param {unknown} target - passable Key
* @param {ERef<import('@agoric/vats').NameHub>} nameHub
*/
const namesOf = async (target, nameHub) => {
const entries = await E(nameHub).entries();
const matches = [];
for (const [name, candidate] of entries) {
if (candidate === target) {
matches.push(name);
}
}
return harden(matches);
};
/**
* Check that an issuer and its brand belong to each other.
*
* TODO: move to ERTP?
*
* @param {Issuer} issuer
* @param {Brand} brand
* @returns {Promise<boolean>} true iff the the brand and issuer match
*/
const checkMutual = (issuer, brand) =>
Promise.all([
E(issuer)
.getBrand()
.then(b => b === brand),
E(brand).isMyIssuer(issuer),
]).then(checks => checks.every(Boolean));
export const BRAND_TO_PURSES_KEY = 'brandToPurses';
const getBrandToPurses = (walletPurses, key) => {
const brandToPurses = provideLazy(walletPurses, key, _k => {
/** @type {MapStore<Brand, PurseRecord[]>} */
const store = makeScalarBigMapStore('purses by brand', {
durable: true,
});
return store;
});
return brandToPurses;
};
const REPAIRED_UNWATCHED_SEATS = 'repairedUnwatchedSeats';
/**
* @param {import('@agoric/vat-data').Baggage} baggage
* @param {SharedParams} shared
*/
export const prepareSmartWallet = (baggage, shared) => {
const { registry: _r, ...passableShared } = shared;
mustMatch(
harden(passableShared),
harden({
agoricNames: M.eref(M.remotable('agoricNames')),
invitationIssuer: IssuerShape,
invitationBrand: BrandShape,
invitationDisplayInfo: DisplayInfoShape,
publicMarshaller: M.remotable('Marshaller'),
zoe: M.eref(M.remotable('ZoeService')),
}),
);
const makeRecorderKit = prepareRecorderKit(baggage, shared.publicMarshaller);
const walletPurses = provide(baggage, BRAND_TO_PURSES_KEY, () => {
trace('make purses by wallet and save in baggage at', BRAND_TO_PURSES_KEY);
/** @type {WeakMapStore<unknown, MapStore<Brand, PurseRecord[]>>} */
const store = makeScalarBigWeakMapStore('purses by wallet', {
durable: true,
});
return store;
});
const makeOfferWatcher = makeOfferWatcherMaker(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 {import('@agoric/zoe/src/contractSupport/recorder.js').RecorderKit<UpdateRecord>} */
const updateRecorderKit = makeRecorderKit(unique.walletStorageNode);
// 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 {import('@agoric/zoe/src/contractSupport/recorder.js').RecorderKit<CurrentWalletRecord>} */
const currentRecorderKit = makeRecorderKit(unique.currentStorageNode);
const nonpreciousState = {
// What purses have reported on construction and by getCurrentAmountNotifier updates.
purseBalances: makeScalarBigMapStore('purse balances', { durable: true }),
updateRecorderKit,
currentRecorderKit,
liveOffers: makeScalarBigMapStore('live offers', { durable: true }),
// Keep seats separate from the offers because we don't want to publish these.
liveOfferSeats: makeScalarBigMapStore('live offer seats', {
durable: true,
}),
liveOfferPayments: makeScalarBigMapStore('live offer payments', {
durable: true,
}),
};
return {
...unique,
...nonpreciousState,
...preciousState,
};
};
const behaviorGuards = {
helper: M.interface('helperFacetI', {
assertUniqueOfferId: M.call(M.string()).returns(),
updateBalance: M.call(PurseShape, AmountShape).optional('init').returns(),
getPurseIfKnownBrand: M.call(BrandShape)
.optional(M.eref(M.remotable()))
.returns(M.promise()),
publishCurrentState: M.call().returns(),
watchPurse: M.call(M.eref(PurseShape)).returns(M.promise()),
repairUnwatchedSeats: M.call().returns(),
updateStatus: M.call(M.any(), M.string()).returns(),
addContinuingOffer: M.call(
M.or(M.number(), M.string()),
AmountShape,
M.remotable('InvitationMaker'),
M.or(M.record(), M.undefined()),
M.string(),
).returns(M.promise()),
purseForBrand: M.call(BrandShape).returns(M.promise()),
}),
deposit: M.interface('depositFacetI', {
receive: M.callWhen(M.await(M.eref(PaymentShape))).returns(AmountShape),
}),
payments: M.interface('payments support', {
withdrawGive: M.call(AmountKeywordRecordShape).returns(
PaymentPKeywordRecordShape,
),
tryReclaimingWithdrawnPayments: M.call(M.string()).returns(M.promise()),
}),
offers: M.interface('offers facet', {
executeOffer: M.call(shape.OfferSpec).returns(M.promise()),
tryExitOffer: M.call(M.scalar()).returns(M.promise()),
}),
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: {
/**
* Assert this ID is unique with respect to what has been stored. The
* wallet doesn't store every offer ID but the offers for which it
* doesn't are unlikely to be impacted by re-use.
*
* @type {(id: string) => void}
*/
assertUniqueOfferId(id) {
const {
liveOffers,
liveOfferSeats,
liveOfferPayments,
offerToInvitationMakers,
offerToPublicSubscriberPaths,
offerToUsedInvitation,
} = this.state;
const used =
liveOffers.has(id) ||
liveOfferSeats.has(id) ||
liveOfferPayments.has(id) ||
offerToInvitationMakers.has(id) ||
offerToPublicSubscriberPaths.has(id) ||
offerToUsedInvitation.has(id);
!used || Fail`cannot re-use offer id ${id}`;
},
/**
* @param {Purse} purse
* @param {Amount<any>} balance
*/
updateBalance(purse, balance) {
const { purseBalances, updateRecorderKit } = this.state;
if (purseBalances.has(purse)) {
purseBalances.set(purse, balance);
} else {
purseBalances.init(purse, balance);
}
void updateRecorderKit.recorder.write({
updated: 'balance',
currentAmount: balance,
});
const { helper } = this.facets;
helper.publishCurrentState();
},
publishCurrentState() {
const {
currentRecorderKit,
offerToUsedInvitation,
offerToPublicSubscriberPaths,
purseBalances,
liveOffers,
} = this.state;
void currentRecorderKit.recorder.write({
purses: [...purseBalances.values()].map(a => ({
brand: a.brand,
balance: a,
})),
offerToUsedInvitation: [...offerToUsedInvitation.entries()],
offerToPublicSubscriberPaths: [
...offerToPublicSubscriberPaths.entries(),
],
liveOffers: [...liveOffers.entries()],
});
},
/** @type {(purse: ERef<Purse>) => 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),
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} ***`,
);
},
});
},
/**
* Provide a purse given a NameHub of issuers and their
* brands.
*
* We currently support only one NameHub, agoricNames, and
* hence one purse per brand. But we store an array of them
* to facilitate a transition to decentralized introductions.
*
* @param {Brand} brand
* @param {ERef<import('@agoric/vats').NameHub>} known - namehub with brand, issuer branches
* @returns {Promise<Purse | undefined>} undefined if brand is not known
*/
async getPurseIfKnownBrand(brand, known) {
const { helper, self } = this.facets;
const brandToPurses = getBrandToPurses(walletPurses, self);
if (brandToPurses.has(brand)) {
const purses = brandToPurses.get(brand);
if (purses.length > 0) {
// UNTIL https://github.com/Agoric/agoric-sdk/issues/6126
// multiple purses
return purses[0].purse;
}
}
const found = await namesOf(brand, E(known).lookup('brand'));
if (found.length === 0) {
return undefined;
}
const [edgeName] = found;
const issuer = await E(known).lookup('issuer', edgeName);
// Even though we rely on this nameHub, double-check
// that the issuer and the brand belong to each other.
if (!(await checkMutual(issuer, brand))) {
// if they don't, it's not a "known" brand in a coherent way
return undefined;
}
// Accept the issuer; rely on it in future offers.
const [displayInfo, purse] = await Promise.all([
E(issuer).getDisplayInfo(),
E(issuer).makeEmptyPurse(),
]);
// adopt edgeName as petname
// NOTE: for decentralized introductions, qualify edgename by nameHub petname
const petname = edgeName;
const assetInfo = { petname, brand, issuer, purse, displayInfo };
appendToStoredArray(brandToPurses, brand, assetInfo);
// NOTE: when we decentralize introduction of issuers,
// process queued payments for this brand.
void helper.watchPurse(purse);
return purse;
},
repairUnwatchedSeats() {
const { state, facets } = this;
const { address, invitationPurse } = state;
const { liveOffers, liveOfferSeats } = state;
const { zoe, agoricNames } = shared;
const { invitationBrand, invitationIssuer } = shared;
if (baggage.has(REPAIRED_UNWATCHED_SEATS)) {
return;
}
baggage.init(REPAIRED_UNWATCHED_SEATS, true);
const invitationFromSpec = makeInvitationsHelper(
zoe,
agoricNames,
invitationBrand,
invitationPurse,
state.offerToInvitationMakers.get,
);
for (const seatId of liveOfferSeats.keys()) {
const offerSpec = liveOffers.get(seatId);
const seat = liveOfferSeats.get(seatId);
const invitation = invitationFromSpec(offerSpec.invitationSpec);
const watcher = makeOfferWatcher(
facets.helper,
offerSpec,
address,
E(invitationIssuer).getAmountOf(invitation),
seat,
);
watchOfferOutcomes(watcher, seat);
}
},
updateStatus(offerStatus, address) {
const { state, facets } = this;
console.info('wallet', address, 'offerStatus', offerStatus);
void state.updateRecorderKit.recorder.write({
updated: 'offerStatus',
status: offerStatus,
});
if ('numWantsSatisfied' in offerStatus) {
if (state.liveOfferSeats.has(offerStatus.id)) {
state.liveOfferSeats.delete(offerStatus.id);
}
if (state.liveOfferPayments.has(offerStatus.id)) {
state.liveOfferPayments.delete(offerStatus.id);
}
if (state.liveOffers.has(offerStatus.id)) {
state.liveOffers.delete(offerStatus.id);
// This might get skipped in subsequent passes, since we .delete()
// the first time through
facets.helper.publishCurrentState();
}
}
},
async addContinuingOffer(
offerId,
invitationAmount,
invitationMakers,
publicSubscribers,
address,
) {
const { state, facets } = this;
state.offerToUsedInvitation.init(offerId, invitationAmount);
state.offerToInvitationMakers.init(offerId, invitationMakers);
const pathMap = await objectMapStoragePath(publicSubscribers);
if (pathMap) {
console.info('wallet', address, 'recording pathMap', pathMap);
state.offerToPublicSubscriberPaths.init(offerId, pathMap);
}
facets.helper.publishCurrentState();
},
/**
* @param {Brand} brand
* @returns {Promise<Purse>}
*/
async purseForBrand(brand) {
const { state, facets } = this;
const { registry, invitationBrand } = shared;
if (registry.has(brand)) {
// @ts-expect-error virtual purse
return E(state.bank).getPurse(brand);
} else if (invitationBrand === brand) {
return state.invitationPurse;
}
const purse = await facets.helper.getPurseIfKnownBrand(
brand,
shared.agoricNames,
);
if (purse) {
return purse;
}
throw Fail`cannot find/make purse for ${brand}`;
},
},
/**
* 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 in durable storage.
*
* @param {Payment} payment
* @returns {Promise<Amount>}
* @throws if there's not yet a purse, though the payment is held to try again when there is
*/
async receive(payment) {
const {
state,
facets: { helper },
} = this;
const { paymentQueues: queues, bank, invitationPurse } = 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);
return E(purse).deposit(payment);
} else if (invitationBrand === brand) {
// @ts-expect-error narrow assetKind to 'set'
return E(invitationPurse).deposit(payment);
}
const purse = await helper.getPurseIfKnownBrand(
brand,
shared.agoricNames,
);
if (purse) {
return E(purse).deposit(payment);
}
// When there is no purse, save the payment into a queue.
// It's not yet ever read but a future version of the contract can
appendToStoredArray(queues, brand, payment);
throw Fail`cannot deposit payment with brand ${brand}: no purse`;
},
},
payments: {
/**
* @param {AmountKeywordRecord} give
* @param {OfferId} offerId
* @returns {PaymentPKeywordRecord}
*/
withdrawGive(give, offerId) {
const { state, facets } = this;
/** @type {MapStore<Brand, Payment>} */
const brandPaymentRecord = makeScalarBigMapStore('paymentToBrand', {
durable: true,
});
state.liveOfferPayments.init(offerId, brandPaymentRecord);
// Add each payment to liveOfferPayments as it is withdrawn. If
// there's an error partway through, we can recover the withdrawals.
return objectMap(give, amount => {
/** @type {Promise<Purse>} */
const purseP = facets.helper.purseForBrand(amount.brand);
const paymentP = E(purseP).withdraw(amount);
void E.when(
paymentP,
payment => brandPaymentRecord.init(amount.brand, payment),
e => {
// recovery will be handled by tryReclaimingWithdrawnPayments()
console.log(`Payment withdrawal failed.`, offerId, e);
},
);
return paymentP;
});
},
async tryReclaimingWithdrawnPayments(offerId) {
const { state, facets } = this;
const { liveOfferPayments } = state;
if (liveOfferPayments.has(offerId)) {
const brandPaymentRecord = liveOfferPayments.get(offerId);
if (!brandPaymentRecord) {
return Promise.resolve(undefined);
}
// Use allSettled to ensure we attempt all the deposits, regardless of
// individual rejections.
return Promise.allSettled(
Array.from(brandPaymentRecord.entries()).map(async ([b, p]) => {
// Wait for the withdrawal to complete. This protects against a
// race when updating paymentToPurse.
const purseP = facets.helper.purseForBrand(b);
// Now send it back to the purse.
return E(purseP).deposit(p);
}),
);
}
},
},
offers: {
/**
* Take an offer description provided in capData, augment it with payments and call zoe.offer()
*
* @param {OfferSpec} offerSpec
* @returns {Promise<void>} after the offer has been both seated and exited by Zoe.
* @throws if any parts of the offer can be determined synchronously to be invalid
*/
async executeOffer(offerSpec) {
const { facets, state } = this;
const { address, invitationPurse } = state;
const { zoe, agoricNames } = shared;
const { invitationBrand, invitationIssuer } = shared;
facets.helper.assertUniqueOfferId(String(offerSpec.id));
await null;
let seatRef;
let watcher;
try {
const invitationFromSpec = makeInvitationsHelper(
zoe,
agoricNames,
invitationBrand,
invitationPurse,
state.offerToInvitationMakers.get,
);
console.info(
'wallet',
address,
'starting executeOffer',
offerSpec.id,
);
// 1. Prepare values and validate synchronously.
const { proposal } = offerSpec;
const invitation = invitationFromSpec(offerSpec.invitationSpec);
const [paymentKeywordRecord, invitationAmount] = await Promise.all([
proposal?.give &&
deeplyFulfilledObject(
facets.payments.withdrawGive(proposal.give, offerSpec.id),
),
E(invitationIssuer).getAmountOf(invitation),
]);
// 2. Begin executing offer
// No explicit signal to user that we reached here but if anything above
// failed they'd get an 'error' status update.
/** @type {UserSeat} */
seatRef = await E(zoe).offer(
invitation,
proposal,
paymentKeywordRecord,
offerSpec.offerArgs,
);
console.info('wallet', address, offerSpec.id, 'seated');
watcher = makeOfferWatcher(
facets.helper,
facets.deposit,
offerSpec,
address,
invitationAmount,
seatRef,
);
state.liveOffers.init(offerSpec.id, offerSpec);
state.liveOfferSeats.init(offerSpec.id, seatRef);
watchOfferOutcomes(watcher, seatRef);
facets.helper.publishCurrentState();
} catch (err) {
console.error('OFFER ERROR:', err);
// Notify the user
if (watcher) {
watcher.helper.updateStatus({ error: err.toString() });
} else {
facets.helper.updateStatus(
{
error: err.toString(),
...offerSpec,
},
address,
);
}
if (offerSpec?.proposal?.give) {
facets.payments
.tryReclaimingWithdrawnPayments(offerSpec.id)
.catch(e =>
console.error('recovery failed reclaiming payments', e),
);
}
if (seatRef) {
void E.when(E(seatRef).hasExited(), hasExited => {
if (!hasExited) {
void E(seatRef).tryExit();
}
});
}
throw err;
}
},
/**
* Take an offer's id, look up its seat, try to exit.
*
* @param {OfferId} offerId
* @returns {Promise<void>}
* @throws if the seat can't be found or E(seatRef).tryExit() fails.
*/
async tryExitOffer(offerId) {
const seatRef = this.state.liveOfferSeats.get(offerId);
await E(seatRef).tryExit();
},
},
self: {
/**
* Umarshals the actionCapData and delegates to the appropriate action handler.
*
* @param {import('@endo/marshal').CapData<string>} actionCapData of type BridgeAction
* @param {boolean} [canSpend]
* @returns {Promise<void>}
*/
handleBridgeAction(actionCapData, canSpend = false) {
const { publicMarshaller } = shared;
const { offers } = this.facets;
/** @param {Error} err */
const recordError = err => {
const { address, updateRecorderKit } = this.state;
console.error('wallet', address, 'handleBridgeAction error:', err);
void updateRecorderKit.recorder.write({
updated: 'walletAction',
status: { error: err.message },
});
};
// use E.when to retain distributed stack trace
return E.when(
E(publicMarshaller).fromCapData(actionCapData),
/** @param {BridgeAction} action */
action => {
try {
switch (action.method) {
case 'executeOffer': {
canSpend || Fail`executeOffer requires spend authority`;
return offers.executeOffer(action.offer);
}
case 'tryExitOffer': {
assert(canSpend, 'tryExitOffer requires spend authority');
return offers.tryExitOffer(action.offerId);
}
default: {
throw Fail`invalid handle bridge action ${q(action)}`;
}
}
} catch (err) {
// record synchronous error in the action delegator above
// but leave async rejections alone because the offer handler recorded them
// with greater detail
recordError(err);
}
},
// record errors in the unserialize and leave the rejection handled
recordError,
);
},
getDepositFacet() {
return this.facets.deposit;
},
getOffersFacet() {
return this.facets.offers;
},
/** @deprecated use getPublicTopics */
getCurrentSubscriber() {
return this.state.currentRecorderKit.subscriber;
},
/** @deprecated use getPublicTopics */
getUpdatesSubscriber() {
return this.state.updateRecorderKit.subscriber;
},
getPublicTopics() {
const {
state: { currentRecorderKit, updateRecorderKit },
} = this;
return harden({
current: {
description: 'Current state of wallet',
subscriber: currentRecorderKit.subscriber,
storagePath: currentRecorderKit.recorder.getStoragePath(),
},
updates: {
description: 'Changes to wallet',
subscriber: updateRecorderKit.subscriber,
storagePath: updateRecorderKit.recorder.getStoragePath(),
},
});
},
},
},
{
finish: ({ state, facets }) => {
const { invitationPurse } = state;
const { helper } = facets;
void helper.watchPurse(invitationPurse);
helper.repairUnwatchedSeats();
},
},
);
/**
* @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,