-
Notifications
You must be signed in to change notification settings - Fork 212
/
test-psm-integration.js
432 lines (367 loc) · 13.7 KB
/
test-psm-integration.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
import { test as anyTest } from '@agoric/zoe/tools/prepare-test-env-ava.js';
import { AmountMath, makeIssuerKit } from '@agoric/ertp';
import { buildRootObject as buildPSMRootObject } from '@agoric/vats/src/core/boot-psm.js';
import '@agoric/vats/src/core/types.js';
import { Stable } from '@agoric/vats/src/tokens.js';
import {
mockDProxy,
mockPsmBootstrapArgs,
} from '@agoric/vats/tools/boot-test-utils.js';
import { eventLoopIteration } from '@agoric/zoe/tools/eventLoopIteration.js';
import { E } from '@endo/far';
import { NonNullish } from '@agoric/assert';
import { coalesceUpdates } from '@agoric/smart-wallet/src/utils.js';
import { INVITATION_MAKERS_DESC } from '../../src/econCommitteeCharter.js';
import { makeDefaultTestContext } from './contexts.js';
import { headValue, withAmountUtils } from '../supports.js';
/**
* @type {import('ava').TestFn<Awaited<ReturnType<makeDefaultTestContext>>
* & {consume: import('@agoric/inter-protocol/src/proposals/econ-behaviors.js').EconomyBootstrapPowers['consume']}>
* }
*/
const test = anyTest;
const committeeAddress = 'psmTestAddress';
const makePsmTestSpace = async log => {
const psmParams = {
anchorAssets: [{ denom: 'ibc/usdc1234', keyword: 'AUSD' }],
economicCommitteeAddresses: { aMember: committeeAddress },
argv: { bootMsg: {} },
};
const psmVatRoot = await buildPSMRootObject(
{
logger: log,
D: mockDProxy,
},
psmParams,
);
void psmVatRoot.bootstrap(...mockPsmBootstrapArgs(log));
// @ts-expect-error cast
return /** @type {ChainBootstrapSpace} */ (psmVatRoot.getPromiseSpace());
};
test.before(async t => {
// @ts-expect-error cast
t.context = await makeDefaultTestContext(t, makePsmTestSpace);
});
/**
* @param {import('@agoric/smart-wallet/src/smartWallet.js').CurrentWalletRecord} record
* @param {Brand<'nat'>} brand
*/
const currentPurseBalance = (record, brand) => {
const purses = Array.from(record.purses.values());
const match = purses.find(b => b.brand === brand);
if (!match) {
console.debug('purses', ...purses);
assert.fail(`${brand} not found in record`);
}
return match.balance.value;
};
test('null swap', async t => {
const { anchor } = t.context;
const { agoricNames } = await E.get(t.context.consume);
const mintedBrand = await E(agoricNames).lookup('brand', 'IST');
const { getBalanceFor, wallet } = await t.context.provideWalletAndBalances(
'agoric1nullswap',
);
const offersFacet = wallet.getOffersFacet();
const psmInstance = await E(agoricNames).lookup('instance', 'psm-IST-AUSD');
/** @type {import('@agoric/smart-wallet/src/invitations').ContractInvitationSpec} */
const invitationSpec = {
source: 'contract',
instance: psmInstance,
publicInvitationMaker: 'makeGiveMintedInvitation',
};
/** @type {import('@agoric/smart-wallet/src/offers').OfferSpec} */
const offerSpec = {
id: 1,
invitationSpec,
proposal: {
// empty amounts
give: { In: AmountMath.makeEmpty(mintedBrand) },
want: { Out: anchor.makeEmpty() },
},
};
// let promises settle to notify brands and create purses
await eventLoopIteration();
await offersFacet.executeOffer(offerSpec);
await eventLoopIteration();
t.is(await E.get(getBalanceFor(anchor.brand)).value, 0n);
t.is(await E.get(getBalanceFor(mintedBrand)).value, 0n);
// success if nothing threw
t.pass();
});
// we test this direciton of swap because wanting anchor would require the PSM to have anchor in it first
test('want stable', async t => {
const { anchor } = t.context;
const { agoricNames } = await E.get(t.context.consume);
const swapSize = 10_000n;
t.log('Start the PSM to ensure brands are registered');
const psmInstance = await E(agoricNames).lookup('instance', 'psm-IST-AUSD');
const stableBrand = await E(agoricNames).lookup('brand', Stable.symbol);
const { getBalanceFor, wallet } = await t.context.provideWalletAndBalances(
'agoric1wantstable',
);
const offersFacet = wallet.getOffersFacet();
t.assert(offersFacet, 'undefined offersFacet');
// let promises settle to notify brands and create purses
await eventLoopIteration();
t.is(await E.get(getBalanceFor(anchor.brand)).value, 0n);
t.log('Fund the wallet');
assert(anchor.mint);
const payment = anchor.mint.mintPayment(anchor.make(swapSize));
// @ts-expect-error deposit does take a FarRef<Payment>
await wallet.getDepositFacet().receive(payment);
t.log('Prepare the swap');
/** @type {import('@agoric/smart-wallet/src/invitations').ContractInvitationSpec} */
const invitationSpec = {
source: 'contract',
instance: psmInstance,
publicInvitationMaker: 'makeWantMintedInvitation',
};
/** @type {import('@agoric/smart-wallet/src/offers').OfferSpec} */
const offerSpec = {
id: 1,
invitationSpec,
proposal: {
give: { In: anchor.make(swapSize) },
want: {},
},
};
t.log('Execute the swap');
await offersFacet.executeOffer(offerSpec);
await eventLoopIteration();
t.is(await E.get(getBalanceFor(anchor.brand)).value, 0n);
t.is(await E.get(getBalanceFor(stableBrand)).value, swapSize); // assume 0% fee
});
test('govern offerFilter', async t => {
const { anchor, invitationBrand } = t.context;
const { agoricNames, psmKit, zoe } = await E.get(t.context.consume);
const { psm: psmInstance } = await E(psmKit).get(anchor.brand);
const wallet = await t.context.simpleProvideWallet(committeeAddress);
const computedState = coalesceUpdates(
E(wallet).getUpdatesSubscriber(),
invitationBrand,
);
const currentSub = E(wallet).getCurrentSubscriber();
const offersFacet = wallet.getOffersFacet();
const econCharter = await E(agoricNames).lookup(
'instance',
'econCommitteeCharter',
);
const economicCommittee = await E(agoricNames).lookup(
'instance',
'economicCommittee',
);
await eventLoopIteration();
/**
* get invitation details the way a user would
*
* @param {string} desc
* @param {number} len
* @param {any} balances XXX please improve this
* @returns {Promise<[{description: string, instance: Instance}]>}
*/
const getInvitationFor = async (desc, len, balances) =>
// @ts-expect-error TS can't tell that it's going to satisfy the @returns.
E(E(zoe).getInvitationIssuer())
.getBrand()
.then(brand => {
t.is(
brand,
invitationBrand,
'invitation brand from context matches zoe',
);
/** @type {Amount<'set'>} */
const invitationsAmount = NonNullish(balances.get(brand));
t.is(invitationsAmount?.value.length, len, 'invitation count');
return invitationsAmount.value.filter(i => i.description === desc);
});
const proposeInvitationDetails = await getInvitationFor(
INVITATION_MAKERS_DESC,
2,
computedState.balances,
);
t.is(proposeInvitationDetails[0].description, INVITATION_MAKERS_DESC);
t.is(proposeInvitationDetails[0].instance, econCharter, 'econCharter');
t.is(
// @ts-expect-error cast amount kind
currentPurseBalance(await headValue(currentSub), invitationBrand).length,
2,
'two invitations deposited',
);
// The purse has the invitation to get the makers ///////////
/** @type {import('@agoric/smart-wallet/src/invitations').PurseInvitationSpec} */
const getInvMakersSpec = {
source: 'purse',
instance: econCharter,
description: INVITATION_MAKERS_DESC,
};
/** @type {import('@agoric/smart-wallet/src/offers').OfferSpec} */
const invMakersOffer = {
id: 44,
invitationSpec: getInvMakersSpec,
proposal: {},
};
await offersFacet.executeOffer(invMakersOffer);
/** @type {import('@agoric/smart-wallet/src/smartWallet.js').CurrentWalletRecord} */
let currentState = await headValue(currentSub);
t.is(
// @ts-expect-error cast amount kind
currentPurseBalance(currentState, invitationBrand).length,
1,
'one invitation consumed, one left',
);
t.deepEqual(Object.keys(currentState.offerToUsedInvitation), ['44']);
t.is(
currentState.offerToUsedInvitation[44].value[0].description,
'charter member invitation',
);
// Call for a vote ////////////////////////////////
/** @type {import('@agoric/smart-wallet/src/invitations').ContinuingInvitationSpec} */
const proposeInvitationSpec = {
source: 'continuing',
previousOffer: 44,
invitationMakerName: 'VoteOnPauseOffers',
invitationArgs: harden([psmInstance, ['wantStable'], 2n]),
};
/** @type {import('@agoric/smart-wallet/src/offers').OfferSpec} */
const proposalOfferSpec = {
id: 45,
invitationSpec: proposeInvitationSpec,
proposal: {},
};
await offersFacet.executeOffer(proposalOfferSpec);
await eventLoopIteration();
// vote /////////////////////////
const committeePublic = E(zoe).getPublicFacet(economicCommittee);
const questions = await E(committeePublic).getOpenQuestions();
const question = E(committeePublic).getQuestion(questions[0]);
const { positions, issue, electionType, questionHandle } = await E(
question,
).getDetails();
t.is(electionType, 'offer_filter');
const yesPosition = harden([positions[0]]);
t.deepEqual(issue.strings, ['wantStable']);
t.deepEqual(yesPosition, [{ strings: ['wantStable'] }]);
const voteInvitationDetails = await getInvitationFor(
'Voter0',
1,
computedState.balances,
);
t.is(voteInvitationDetails.length, 1);
const voteInvitationDetail = voteInvitationDetails[0];
t.is(voteInvitationDetail.description, 'Voter0');
t.is(voteInvitationDetail.instance, economicCommittee);
/** @type {import('@agoric/smart-wallet/src/invitations').PurseInvitationSpec} */
const getCommitteeInvMakersSpec = {
source: 'purse',
instance: economicCommittee,
description: 'Voter0',
};
/** @type {import('@agoric/smart-wallet/src/offers').OfferSpec} */
const committeeInvMakersOffer = {
id: 46,
invitationSpec: getCommitteeInvMakersSpec,
proposal: {},
};
await offersFacet.executeOffer(committeeInvMakersOffer);
currentState = await headValue(currentSub);
t.is(
// @ts-expect-error cast amount kind
currentPurseBalance(currentState, invitationBrand).length,
0,
'last invitation consumed, none left',
);
t.deepEqual(Object.keys(currentState.offerToUsedInvitation), ['44', '46']);
// 44 tested above
t.is(currentState.offerToUsedInvitation[46].value[0].description, 'Voter0');
/** @type {import('@agoric/smart-wallet/src/invitations').ContinuingInvitationSpec} */
const getVoteSpec = {
source: 'continuing',
previousOffer: 46,
invitationMakerName: 'makeVoteInvitation',
invitationArgs: harden([yesPosition, questionHandle]),
};
/** @type {import('@agoric/smart-wallet/src/offers').OfferSpec} */
const voteOffer = {
id: 47,
invitationSpec: getVoteSpec,
proposal: {},
};
await offersFacet.executeOffer(voteOffer);
await eventLoopIteration();
// can't advance the clock, so the vote won't close. Call it enuf that the
// vote didn't raise an error.
});
test('deposit unknown brand', async t => {
const rial = withAmountUtils(makeIssuerKit('rial'));
assert(rial.mint);
const wallet = await t.context.simpleProvideWallet('agoric1queue');
const payment = rial.mint.mintPayment(rial.make(1_000n));
// @ts-expect-error deposit does take a FarRef<Payment>
const result = await wallet.getDepositFacet().receive(harden(payment));
// successful request but not deposited
t.deepEqual(result, { brand: rial.brand, value: 0n });
});
test.failing('deposit > 1 payment to unknown brand', async t => {
const rial = withAmountUtils(makeIssuerKit('rial'));
const wallet = await t.context.simpleProvideWallet('agoric1queue');
for await (const _ of [1, 2]) {
const payment = rial.mint.mintPayment(rial.make(1_000n));
// @ts-expect-error deposit does take a FarRef<Payment>
const result = await wallet.getDepositFacet().receive(harden(payment));
// successful request but not deposited
t.deepEqual(result, { brand: rial.brand, value: 0n });
}
});
// XXX belongs in smart-wallet package, but needs lots of set-up that's handy here.
test('recover when some withdrawals succeed and others fail', async t => {
const { fromEntries } = Object;
const { make } = AmountMath;
const { anchor } = t.context;
const { agoricNames, bankManager } = t.context.consume;
const getBalance = (addr, brand) => {
const bank = E(bankManager).getBankForAddress(addr);
const purse = E(bank).getPurse(brand);
return E(purse).getCurrentAmount();
};
const namedBrands = kws =>
Promise.all(
kws.map(kw =>
E(agoricNames)
.lookup('brand', kw)
.then(b => [kw, b]),
),
).then(fromEntries);
t.log('Johnny has 10 AUSD');
const jAddr = 'addrForJohnny';
const smartWallet = await t.context.simpleProvideWallet(jAddr);
await E(E(smartWallet).getDepositFacet()).receive(
// @ts-expect-error FarRef grumble
E(anchor.mint).mintPayment(make(anchor.brand, 10n)),
);
t.deepEqual(await getBalance(jAddr, anchor.brand), make(anchor.brand, 10n));
t.log('He accidentally offers 10 BLD as well in a trade for IST');
const instance = await E(agoricNames).lookup('instance', 'psm-IST-AUSD');
const brand = await namedBrands(['BLD', 'IST']);
const proposal = harden({
give: { Anchor: make(anchor.brand, 10n), Oops: make(brand.BLD, 10n) },
want: { Proceeds: make(brand.IST, 1n) },
});
await E(smartWallet.getOffersFacet()).executeOffer({
id: '1',
invitationSpec: {
source: 'contract',
instance,
publicInvitationMaker: 'makeWantMintedInvitation',
invitationArgs: [],
},
proposal,
});
t.log('He still has 10 AUSD');
t.deepEqual(await getBalance(jAddr, anchor.brand), make(anchor.brand, 10n));
});
test.todo('bad offer schema');
test.todo('not enough funds');
test.todo(
'a faulty issuer that never returns and additional offers can still flow',
);