-
Notifications
You must be signed in to change notification settings - Fork 212
/
offerWatcher.js
329 lines (307 loc) · 10.5 KB
/
offerWatcher.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
import { E, passStyleOf } from '@endo/far';
import { isUpgradeDisconnection } from '@agoric/internal/src/upgrade-api.js';
import { prepareExoClassKit, watchPromise } from '@agoric/vat-data';
import { M } from '@agoric/store';
import {
PaymentPKeywordRecordShape,
SeatShape,
} from '@agoric/zoe/src/typeGuards.js';
import { AmountShape } from '@agoric/ertp/src/typeGuards.js';
import { deeplyFulfilledObject, objectMap } from '@agoric/internal';
import { UNPUBLISHED_RESULT } from './offers.js';
/**
* @import {OfferSpec} from './offers.js';
* @import {ContinuingOfferResult} from './types.js';
* @import {Passable} from '@endo/pass-style';
* @import {PromiseWatcher} from '@agoric/swingset-liveslots';
* @import {Baggage} from '@agoric/vat-data';
* @import {Vow, VowTools} from '@agoric/vow';
*/
/**
* @template {any} T
* @typedef {PromiseWatcher<T, [UserSeat]>} OfferPromiseWatcher<T, [UserSeat]
*/
/**
* @typedef {{
* resultWatcher: OfferPromiseWatcher<Passable>;
* numWantsWatcher: OfferPromiseWatcher<number>;
* paymentWatcher: OfferPromiseWatcher<PaymentPKeywordRecord>;
* }} OutcomeWatchers
*/
/** @param {VowTools} vowTools */
const makeWatchForOfferResult = ({ watch }) => {
/**
* @param {OutcomeWatchers} watchers
* @param {UserSeat} seat
* @returns {Vow<void>} Vow that resolves when offer result has been processed
* by the resultWatcher
*/
const watchForOfferResult = ({ resultWatcher }, seat) => {
// Offer result may be anything, including a Vow, so watch it durably.
return watch(E(seat).getOfferResult(), resultWatcher, seat);
};
return watchForOfferResult;
};
/**
* @param {OutcomeWatchers} watchers
* @param {UserSeat} seat
*/
const watchForNumWants = ({ numWantsWatcher }, seat) => {
const p = E(seat).numWantsSatisfied();
watchPromise(p, numWantsWatcher, seat);
return p;
};
/**
* @param {OutcomeWatchers} watchers
* @param {UserSeat} seat
*/
const watchForPayout = ({ paymentWatcher }, seat) => {
const p = E(seat).getPayouts();
watchPromise(p, paymentWatcher, seat);
return p;
};
/** @param {VowTools} vowTools */
export const makeWatchOfferOutcomes = vowTools => {
const watchForOfferResult = makeWatchForOfferResult(vowTools);
const { when, allVows } = vowTools;
/**
* @param {OutcomeWatchers} watchers
* @param {UserSeat} seat
*/
const watchOfferOutcomes = (watchers, seat) => {
// Use `when` to get a promise from the vow.
// Unlike `asPromise` this doesn't warn in case of disconnections, which is
// fine since we actually handle the outcome durably through the watchers.
// Only the `executeOffer` caller relies on the settlement of this promise,
// and only in tests.
return when(
allVows([
watchForOfferResult(watchers, seat),
watchForNumWants(watchers, seat),
watchForPayout(watchers, seat),
]),
);
};
return watchOfferOutcomes;
};
const offerWatcherGuard = harden({
helper: M.interface('InstanceAdminStorage', {
updateStatus: M.call(M.any()).returns(),
onNewContinuingOffer: M.call(
M.or(M.number(), M.string()),
AmountShape,
M.any(),
)
.optional(M.record())
.returns(),
publishResult: M.call(M.any()).returns(),
handleError: M.call(M.error()).returns(),
}),
paymentWatcher: M.interface('paymentWatcher', {
onFulfilled: M.call(PaymentPKeywordRecordShape, SeatShape).returns(
M.promise(),
),
onRejected: M.call(M.any(), SeatShape).returns(),
}),
resultWatcher: M.interface('resultWatcher', {
onFulfilled: M.call(M.any(), SeatShape).returns(),
onRejected: M.call(M.any(), SeatShape).returns(),
}),
numWantsWatcher: M.interface('numWantsWatcher', {
onFulfilled: M.call(M.number(), SeatShape).returns(),
onRejected: M.call(M.any(), SeatShape).returns(),
}),
});
/**
* @param {Baggage} baggage
* @param {VowTools} vowTools
*/
export const prepareOfferWatcher = (baggage, vowTools) => {
const watchForOfferResult = makeWatchForOfferResult(vowTools);
return prepareExoClassKit(
baggage,
'OfferWatcher',
offerWatcherGuard,
// XXX walletHelper is `any` because the helper facet is too nested to export its type
/**
* @param {any} walletHelper
* @param {{ receive: (payment: Payment) => Promise<Amount> }} deposit
* @param {OfferSpec} offerSpec
* @param {string} address
* @param {Amount<'set'>} invitationAmount
* @param {UserSeat} seatRef
*/
(walletHelper, deposit, offerSpec, address, invitationAmount, seatRef) => ({
walletHelper,
deposit,
status: offerSpec,
address,
invitationAmount,
seatRef,
}),
{
helper: {
/**
* @param {Record<string, unknown>} offerStatusUpdates
*/
updateStatus(offerStatusUpdates) {
const { state } = this;
state.status = harden({ ...state.status, ...offerStatusUpdates });
state.walletHelper.updateStatus(state.status);
},
/**
* @param {string} offerId
* @param {Amount<'set'>} invitationAmount
* @param {import('./types.js').InvitationMakers} invitationMakers
* @param {import('./types.js').PublicSubscribers} publicSubscribers
*/
onNewContinuingOffer(
offerId,
invitationAmount,
invitationMakers,
publicSubscribers,
) {
const { state } = this;
void state.walletHelper.addContinuingOffer(
offerId,
invitationAmount,
invitationMakers,
publicSubscribers,
);
},
/** @param {Passable | ContinuingOfferResult} result */
publishResult(result) {
const { state, facets } = this;
const passStyle = passStyleOf(result);
// someday can we get TS to type narrow based on the passStyleOf result match?
switch (passStyle) {
case 'bigint':
case 'boolean':
case 'null':
case 'number':
case 'string':
case 'symbol':
case 'undefined':
facets.helper.updateStatus({ result });
break;
case 'copyRecord':
// @ts-expect-error narrowed by passStyle
if ('invitationMakers' in result) {
// save for continuing invitation offer
void facets.helper.onNewContinuingOffer(
String(state.status.id),
state.invitationAmount,
// @ts-expect-error narrowed by passStyle
result.invitationMakers,
result.publicSubscribers,
);
}
facets.helper.updateStatus({ result: UNPUBLISHED_RESULT });
break;
default:
// drop the result
facets.helper.updateStatus({ result: UNPUBLISHED_RESULT });
}
},
/**
* Called when the offer result promise rejects. The other two watchers
* are waiting for particular values out of Zoe but they settle at the
* same time and don't need their own error handling.
*
* @param {Error} err
*/
handleError(err) {
const { facets } = this;
facets.helper.updateStatus({ error: err.toString() });
const { seatRef } = this.state;
void E.when(E(seatRef).hasExited(), hasExited => {
if (!hasExited) {
void E(seatRef).tryExit();
}
});
},
},
/** @type {OutcomeWatchers['paymentWatcher']} */
paymentWatcher: {
async onFulfilled(payouts) {
const { state, facets } = this;
// This will block until all payouts succeed, but user will be updated
// since each payout will trigger its corresponding purse notifier.
const amountPKeywordRecord = objectMap(payouts, paymentRef =>
E.when(paymentRef, payment => state.deposit.receive(payment)),
);
const amounts = await deeplyFulfilledObject(amountPKeywordRecord);
facets.helper.updateStatus({ payouts: amounts });
},
/**
* If promise disconnected, watch again. Or if there's an Error, handle
* it.
*
* @param {Error
* | import('@agoric/internal/src/upgrade-api.js').UpgradeDisconnection} reason
* @param {UserSeat} seat
*/
onRejected(reason, seat) {
const { facets } = this;
if (isUpgradeDisconnection(reason)) {
void watchForPayout(facets, seat);
} else {
facets.helper.handleError(reason);
}
},
},
/** @type {OutcomeWatchers['resultWatcher']} */
resultWatcher: {
onFulfilled(result) {
const { facets } = this;
facets.helper.publishResult(result);
},
/**
* If promise disconnected, watch again. Or if there's an Error, handle
* it.
*
* @param {Error
* | import('@agoric/internal/src/upgrade-api.js').UpgradeDisconnection} reason
* @param {UserSeat} seat
*/
onRejected(reason, seat) {
const { facets } = this;
if (isUpgradeDisconnection(reason)) {
void watchForOfferResult(facets, seat);
} else {
facets.helper.handleError(reason);
}
// throw so the vow watcher propagates the rejection
throw reason;
},
},
/** @type {OutcomeWatchers['numWantsWatcher']} */
numWantsWatcher: {
onFulfilled(numSatisfied) {
const { facets } = this;
facets.helper.updateStatus({ numWantsSatisfied: numSatisfied });
},
/**
* If promise disconnected, watch again.
*
* Errors are handled by the paymentWatcher because numWantsSatisfied()
* and getPayouts() settle the same (they await the same promise and
* then synchronously return a local value).
*
* @param {Error
* | import('@agoric/internal/src/upgrade-api.js').UpgradeDisconnection} reason
* @param {UserSeat} seat
*/
onRejected(reason, seat) {
const { facets } = this;
if (isUpgradeDisconnection(reason)) {
void watchForNumWants(facets, seat);
}
},
},
},
);
};
harden(prepareOfferWatcher);
/** @typedef {ReturnType<typeof prepareOfferWatcher>} MakeOfferWatcher */
/** @typedef {ReturnType<MakeOfferWatcher>} OfferWatcher */