-
Notifications
You must be signed in to change notification settings - Fork 207
/
paymentLedger.js
338 lines (308 loc) · 10.5 KB
/
paymentLedger.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
// @ts-check
import { assert, details as X } from '@agoric/assert';
import { E } from '@agoric/eventual-send';
import { isPromise } from '@agoric/promise-kit';
import { Far } from '@agoric/marshal';
import { makeWeakStore } from '@agoric/store';
import { AmountMath } from './amountMath';
import { makePayment } from './payment';
import { makePurse } from './purse';
import '@agoric/store/exported';
/**
* Make the paymentLedger, the source of truth for the balances of
* payments. All minting and transfer authority originates here.
*
* @param {string} allegedName
* @param {Brand} brand
* @param {AssetKind} assetKind
* @param {DisplayInfo} displayInfo
* @param {ShutdownWithFailure=} optShutdownWithFailure
* @returns {{ issuer: Issuer, mint: Mint }}
*/
export const makePaymentLedger = (
allegedName,
brand,
assetKind,
displayInfo,
optShutdownWithFailure = undefined,
) => {
/** @type {ShutdownWithFailure} */
const shutdownLedgerWithFailure = reason => {
// TODO This should also destroy ledger state.
// See https://github.com/Agoric/agoric-sdk/issues/3434
if (optShutdownWithFailure !== undefined) {
optShutdownWithFailure(reason);
}
throw reason;
};
/** @type {WeakStore<Payment, Amount>} */
const paymentLedger = makeWeakStore('payment');
/** @type {(left: Amount, right: Amount) => Amount } */
const add = (left, right) => AmountMath.add(left, right, brand);
/** @type {(left: Amount, right: Amount) => Amount } */
const subtract = (left, right) => AmountMath.subtract(left, right, brand);
/** @type {(allegedAmount: Amount) => Amount} */
const coerce = allegedAmount => AmountMath.coerce(brand, allegedAmount);
/** @type {(left: Amount, right: Amount) => boolean } */
const isEqual = (left, right) => AmountMath.isEqual(left, right, brand);
/** @type {Amount} */
const emptyAmount = AmountMath.makeEmpty(brand, assetKind);
/**
* Methods like deposit() have an optional second parameter `amount`
* which, if present, is supposed to be equal to the balance of the
* payment. This helper function does that check.
*
* @param {Amount} paymentBalance
* @param {Amount | undefined} amount
* @returns {void}
*/
const assertAmountConsistent = (paymentBalance, amount) => {
if (amount !== undefined) {
assert(
isEqual(amount, paymentBalance),
X`payment balance ${paymentBalance} must equal amount ${amount}`,
);
}
};
/**
* @param {Payment} payment
* @returns {void}
*/
const assertLivePayment = payment => {
assert(paymentLedger.has(payment), X`payment not found for ${allegedName}`);
};
/**
* Reallocate assets from the `payments` passed in to new payments
* created and returned, with balances from `newPaymentBalances`.
* Enforces that total assets are conserved.
*
* Note that this is not the only operation that reallocates assets.
* `purse.deposit` and `purse.withdraw` move assets between a purse and
* a payment, and so must also enforce conservation there.
*
* @param {Payment[]} payments
* @param {Amount[]} newPaymentBalances
* @returns {Payment[]}
*/
const reallocate = (payments, newPaymentBalances) => {
// There may be zero, one, or many payments as input to
// reallocate. We want to protect against someone passing in
// what appears to be multiple payments that turn out to actually
// be the same payment (an aliasing issue). The `combine` method
// legitimately needs to take in multiple payments, but we don't
// need to pay the costs of protecting against aliasing for the
// other uses.
if (payments.length > 1) {
const antiAliasingStore = new Set();
payments.forEach(payment => {
if (antiAliasingStore.has(payment)) {
throw Error('same payment seen twice');
}
antiAliasingStore.add(payment);
});
}
const total = payments.map(paymentLedger.get).reduce(add, emptyAmount);
const newTotal = newPaymentBalances.reduce(add, emptyAmount);
// Invariant check
assert(
isEqual(total, newTotal),
X`rights were not conserved: ${total} vs ${newTotal}`,
);
let newPayments;
try {
// COMMIT POINT
payments.forEach(payment => paymentLedger.delete(payment));
newPayments = newPaymentBalances.map(balance => {
const newPayment = makePayment(allegedName, brand);
paymentLedger.init(newPayment, balance);
return newPayment;
});
} catch (err) {
shutdownLedgerWithFailure(err);
throw err;
}
return harden(newPayments);
};
/** @type {IssuerIsLive} */
const isLive = paymentP => {
return E.when(paymentP, payment => {
return paymentLedger.has(payment);
});
};
/** @type {IssuerGetAmountOf} */
const getAmountOf = paymentP => {
return E.when(paymentP, payment => {
assertLivePayment(payment);
return paymentLedger.get(payment);
});
};
/** @type {IssuerBurn} */
const burn = (paymentP, optAmount = undefined) => {
return E.when(paymentP, payment => {
assertLivePayment(payment);
const paymentBalance = paymentLedger.get(payment);
assertAmountConsistent(paymentBalance, optAmount);
try {
// COMMIT POINT.
paymentLedger.delete(payment);
} catch (err) {
shutdownLedgerWithFailure(err);
throw err;
}
return paymentBalance;
});
};
/** @type {IssuerClaim} */
const claim = (paymentP, optAmount = undefined) => {
return E.when(paymentP, srcPayment => {
assertLivePayment(srcPayment);
const srcPaymentBalance = paymentLedger.get(srcPayment);
assertAmountConsistent(srcPaymentBalance, optAmount);
// Note COMMIT POINT within reallocate.
const [payment] = reallocate([srcPayment], [srcPaymentBalance]);
return payment;
});
};
/** @type {IssuerCombine} */
const combine = (fromPaymentsPArray, optTotalAmount = undefined) => {
// Payments in `fromPaymentsPArray` must be distinct. Alias
// checking is delegated to the `reallocate` function.
return Promise.all(fromPaymentsPArray).then(fromPaymentsArray => {
fromPaymentsArray.every(assertLivePayment);
const totalPaymentsBalance = fromPaymentsArray
.map(paymentLedger.get)
.reduce(add, emptyAmount);
assertAmountConsistent(totalPaymentsBalance, optTotalAmount);
// Note COMMIT POINT within reallocate.
const [payment] = reallocate(fromPaymentsArray, [totalPaymentsBalance]);
return payment;
});
};
/** @type {IssuerSplit} */
// payment to two payments, A and B
const split = (paymentP, paymentAmountA) => {
return E.when(paymentP, srcPayment => {
paymentAmountA = coerce(paymentAmountA);
assertLivePayment(srcPayment);
const srcPaymentBalance = paymentLedger.get(srcPayment);
const paymentAmountB = subtract(srcPaymentBalance, paymentAmountA);
// Note COMMIT POINT within reallocate.
const newPayments = reallocate(
[srcPayment],
[paymentAmountA, paymentAmountB],
);
return newPayments;
});
};
/** @type {IssuerSplitMany} */
const splitMany = (paymentP, amounts) => {
return E.when(paymentP, srcPayment => {
assertLivePayment(srcPayment);
amounts = amounts.map(coerce);
// Note COMMIT POINT within reallocate.
const newPayments = reallocate([srcPayment], amounts);
return newPayments;
});
};
/** @type {MintPayment} */
const mintPayment = newAmount => {
newAmount = coerce(newAmount);
const payment = makePayment(allegedName, brand);
paymentLedger.init(payment, newAmount);
return payment;
};
/**
* Used by the purse code to implement purse.deposit
*
* @param {Amount} currentBalance - the current balance of the purse
* before a deposit
* @param {(newPurseBalance: Amount) => void} updatePurseBalance -
* commit the purse balance
* @param {Payment} srcPayment
* @param {Amount=} optAmount
* @returns {Amount}
*/
const deposit = (
currentBalance,
updatePurseBalance,
srcPayment,
optAmount = undefined,
) => {
if (isPromise(srcPayment)) {
throw TypeError(
`deposit does not accept promises as first argument. Instead of passing the promise (deposit(paymentPromise)), consider unwrapping the promise first: E.when(paymentPromise, (actualPayment => deposit(actualPayment))`,
);
}
assertLivePayment(srcPayment);
const srcPaymentBalance = paymentLedger.get(srcPayment);
// Note: this does not guarantee that optAmount itself is a valid stable amount
assertAmountConsistent(srcPaymentBalance, optAmount);
const newPurseBalance = add(srcPaymentBalance, currentBalance);
try {
// COMMIT POINT
// Move the assets in `srcPayment` into this purse, using up the
// source payment, such that total assets are conserved.
paymentLedger.delete(srcPayment);
updatePurseBalance(newPurseBalance);
} catch (err) {
shutdownLedgerWithFailure(err);
throw err;
}
return srcPaymentBalance;
};
/**
* Used by the purse code to implement purse.withdraw
*
* @param {Amount} currentBalance - the current balance of the purse
* before a withdrawal
* @param {(newPurseBalance: Amount) => void} updatePurseBalance -
* commit the purse balance
* @param {Amount} amount - the amount to be withdrawn
* @returns {Payment}
*/
const withdraw = (currentBalance, updatePurseBalance, amount) => {
amount = coerce(amount);
const newPurseBalance = subtract(currentBalance, amount);
const payment = makePayment(allegedName, brand);
try {
// COMMIT POINT
// Move the withdrawn assets from this purse into a new payment
// which is returned. Total assets must remain conserved.
updatePurseBalance(newPurseBalance);
paymentLedger.init(payment, amount);
} catch (err) {
shutdownLedgerWithFailure(err);
throw err;
}
return payment;
};
const purseMethods = {
deposit,
withdraw,
};
/** @type {Issuer} */
const issuer = Far(`${allegedName} issuer`, {
isLive,
getAmountOf,
burn,
claim,
combine,
split,
splitMany,
getBrand: () => brand,
getAllegedName: () => allegedName,
getAssetKind: () => assetKind,
getDisplayInfo: () => displayInfo,
makeEmptyPurse: () =>
makePurse(allegedName, assetKind, brand, purseMethods),
});
/** @type {Mint} */
const mint = Far(`${allegedName} mint`, {
getIssuer: () => issuer,
mintPayment,
});
return harden({
issuer,
mint,
});
};