agoric 0.18.4 → 0.18.5-dev-800c2bb.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,314 @@
1
+ /* eslint-disable @jessie.js/no-nested-await */
2
+ // @ts-check
3
+ /* eslint-disable func-names */
4
+ /* global globalThis, process, setTimeout */
5
+ import { execFileSync as execFileSyncAmbient } from 'child_process';
6
+ import { Command, CommanderError } from 'commander';
7
+ import { normalizeAddressWithOptions, pollBlocks } from '../lib/chain.js';
8
+ import { getNetworkConfig, makeRpcUtils } from '../lib/rpc.js';
9
+ import {
10
+ findContinuingIds,
11
+ getCurrent,
12
+ getLastUpdate,
13
+ outputActionAndHint,
14
+ sendAction,
15
+ } from '../lib/wallet.js';
16
+
17
+ /** @typedef {import('@agoric/smart-wallet/src/offers.js').OfferSpec} OfferSpec */
18
+
19
+ /**
20
+ * @param {import('anylogger').Logger} _logger
21
+ * @param {{
22
+ * env?: Record<string, string|undefined>,
23
+ * fetch?: typeof window.fetch,
24
+ * stdout?: Pick<import('stream').Writable, 'write'>,
25
+ * stderr?: Pick<import('stream').Writable, 'write'>,
26
+ * execFileSync?: typeof execFileSyncAmbient,
27
+ * delay?: (ms: number) => Promise<void>,
28
+ * }} [io]
29
+ */
30
+ export const makeEconomicCommiteeCommand = (_logger, io = {}) => {
31
+ const {
32
+ // Allow caller to provide access explicitly, but
33
+ // default to conventional ambient IO facilities.
34
+ env = process.env,
35
+ stdout = process.stdout,
36
+ stderr = process.stderr,
37
+ fetch = globalThis.fetch,
38
+ execFileSync = execFileSyncAmbient,
39
+ delay = ms => new Promise(resolve => setTimeout(resolve, ms)),
40
+ } = io;
41
+
42
+ const ec = new Command('ec').description('Economic Committee commands');
43
+
44
+ /** @param {string} literalOrName */
45
+ const normalizeAddress = literalOrName =>
46
+ normalizeAddressWithOptions(literalOrName, { keyringBackend: 'test' });
47
+
48
+ /** @type {(info: unknown, indent?: unknown) => boolean } */
49
+ const show = (info, indent) =>
50
+ stdout.write(`${JSON.stringify(info, null, indent ? 2 : undefined)}\n`);
51
+
52
+ const abortIfSeen = (instanceName, found) => {
53
+ const done = found.filter(it => it.instanceName === instanceName);
54
+ if (done.length > 0) {
55
+ console.warn(`invitation to ${instanceName} already accepted`, done);
56
+ throw new CommanderError(1, 'EALREADY', `already accepted`);
57
+ }
58
+ };
59
+
60
+ /**
61
+ * Make an offer from agoricNames, wallet status; sign and broadcast it,
62
+ * given a sendFrom address; else print it.
63
+ *
64
+ * @param {{
65
+ * toOffer: (agoricNames: *, current: import('@agoric/smart-wallet/src/smartWallet').CurrentWalletRecord | undefined) => OfferSpec,
66
+ * sendFrom?: string | undefined,
67
+ * instanceName?: string,
68
+ * }} detail
69
+ * @param {Awaited<ReturnType<makeRpcUtils>>} [optUtils]
70
+ */
71
+ const processOffer = async function ({ toOffer, sendFrom }, optUtils) {
72
+ const networkConfig = await getNetworkConfig(env);
73
+ const utils = await (optUtils || makeRpcUtils({ fetch }));
74
+ const { agoricNames, readLatestHead } = utils;
75
+
76
+ let current;
77
+ if (sendFrom) {
78
+ current = await getCurrent(sendFrom, { readLatestHead });
79
+ }
80
+
81
+ const offer = toOffer(agoricNames, current);
82
+ if (!sendFrom) {
83
+ outputActionAndHint(
84
+ { method: 'executeOffer', offer },
85
+ { stdout, stderr },
86
+ );
87
+ return;
88
+ }
89
+
90
+ const result = await sendAction(
91
+ { method: 'executeOffer', offer },
92
+ {
93
+ keyring: { backend: 'test' }, // XXX
94
+ from: sendFrom,
95
+ verbose: false,
96
+ ...networkConfig,
97
+ execFileSync,
98
+ stdout,
99
+ delay,
100
+ },
101
+ );
102
+ assert(result); // not dry-run
103
+ const { timestamp, txhash, height } = result;
104
+ console.error('wallet action is broadcast:');
105
+ show({ timestamp, height, offerId: offer.id, txhash });
106
+ const checkInWallet = async blockInfo => {
107
+ const [state, update] = await Promise.all([
108
+ getCurrent(sendFrom, { readLatestHead }),
109
+ getLastUpdate(sendFrom, { readLatestHead }),
110
+ readLatestHead(`published.wallet.${sendFrom}`),
111
+ ]);
112
+ if (update.updated === 'offerStatus' && update.status.id === offer.id) {
113
+ return blockInfo;
114
+ }
115
+ const info = await findContinuingIds(state, agoricNames);
116
+ const done = info.filter(it => it.offerId === offer.id);
117
+ if (!(done.length > 0)) throw Error('retry');
118
+ return blockInfo;
119
+ };
120
+ const blockInfo = await pollBlocks({
121
+ retryMessage: 'offer not yet in block',
122
+ ...networkConfig,
123
+ execFileSync,
124
+ delay,
125
+ })(checkInWallet);
126
+ console.error('offer accepted in block');
127
+ show(blockInfo);
128
+ };
129
+
130
+ ec.command('committee')
131
+ .description('accept invitation to join the economic committee')
132
+ .option('--voter <number>', 'Voter number', Number, 0)
133
+ .option(
134
+ '--offerId <string>',
135
+ 'Offer id',
136
+ String,
137
+ `ecCommittee-${Date.now()}`,
138
+ )
139
+ .option(
140
+ '--send-from <name-or-address>',
141
+ 'Send from address',
142
+ normalizeAddress,
143
+ )
144
+ .action(async function (opts) {
145
+ /** @type {Parameters<typeof processOffer>[0]['toOffer']} */
146
+ const toOffer = (agoricNames, current) => {
147
+ const instance = agoricNames.instance.economicCommittee;
148
+ assert(instance, `missing economicCommittee`);
149
+
150
+ if (current) {
151
+ const found = findContinuingIds(current, agoricNames);
152
+ abortIfSeen('economicCommittee', found);
153
+ }
154
+
155
+ return {
156
+ id: opts.offerId,
157
+ invitationSpec: {
158
+ source: 'purse',
159
+ instance,
160
+ description: `Voter${opts.voter}`,
161
+ },
162
+ proposal: {},
163
+ };
164
+ };
165
+
166
+ await processOffer({
167
+ toOffer,
168
+ instanceName: 'economicCommittee',
169
+ ...opts,
170
+ });
171
+ });
172
+
173
+ ec.command('charter')
174
+ .description('accept the charter invitation')
175
+ .option('--offerId <string>', 'Offer id', String, `ecCharter-${Date.now()}`)
176
+ .option(
177
+ '--send-from <name-or-address>',
178
+ 'Send from address',
179
+ normalizeAddress,
180
+ )
181
+ .action(async function (opts) {
182
+ /** @type {Parameters<typeof processOffer>[0]['toOffer']} */
183
+ const toOffer = (agoricNames, current) => {
184
+ const instance = agoricNames.instance.econCommitteeCharter;
185
+ assert(instance, `missing econCommitteeCharter`);
186
+
187
+ if (current) {
188
+ const found = findContinuingIds(current, agoricNames);
189
+ abortIfSeen('econCommitteeCharter', found);
190
+ }
191
+
192
+ return {
193
+ id: opts.offerId,
194
+ invitationSpec: {
195
+ source: 'purse',
196
+ instance,
197
+ description: 'charter member invitation',
198
+ },
199
+ proposal: {},
200
+ };
201
+ };
202
+
203
+ await processOffer({
204
+ toOffer,
205
+ instanceName: 'econCommitteeCharter',
206
+ ...opts,
207
+ });
208
+ });
209
+
210
+ ec.command('find-continuing-id')
211
+ .description('print id of specified voting continuing invitation')
212
+ .requiredOption(
213
+ '--from <name-or-address>',
214
+ 'from address',
215
+ normalizeAddress,
216
+ )
217
+ .requiredOption('--for <string>', 'description of the invitation')
218
+ .action(async opts => {
219
+ const { agoricNames, readLatestHead } = await makeRpcUtils({ fetch });
220
+ const current = await getCurrent(opts.from, { readLatestHead });
221
+
222
+ const known = findContinuingIds(current, agoricNames);
223
+ if (!known) {
224
+ console.error('No continuing ids found');
225
+ return;
226
+ }
227
+ const match = known.find(r => r.description === opts.for);
228
+ if (!match) {
229
+ console.error(`No match found for '${opts.for}'`);
230
+ return;
231
+ }
232
+
233
+ console.log(match.offerId);
234
+ });
235
+
236
+ ec.command('find-continuing-ids')
237
+ .description('print records of voting continuing invitations')
238
+ .requiredOption(
239
+ '--from <name-or-address>',
240
+ 'from address',
241
+ normalizeAddress,
242
+ )
243
+ .action(async opts => {
244
+ const { agoricNames, readLatestHead } = await makeRpcUtils({ fetch });
245
+ const current = await getCurrent(opts.from, { readLatestHead });
246
+
247
+ const found = findContinuingIds(current, agoricNames);
248
+ found.forEach(it => show({ ...it, address: opts.from }));
249
+ });
250
+
251
+ ec.command('vote')
252
+ .description('vote on a question (hard-coded for now))')
253
+ .option('--offerId <number>', 'Offer id', String, `ecVote-${Date.now()}`)
254
+ .requiredOption(
255
+ '--forPosition <number>',
256
+ 'index of one position to vote for (within the question description.positions); ',
257
+ Number,
258
+ )
259
+ .requiredOption(
260
+ '--send-from <name-or-address>',
261
+ 'Send from address',
262
+ normalizeAddress,
263
+ )
264
+ .action(async function (opts) {
265
+ const utils = await makeRpcUtils({ fetch });
266
+ const { readLatestHead } = utils;
267
+
268
+ const info = await readLatestHead(
269
+ 'published.committees.Economic_Committee.latestQuestion',
270
+ ).catch(err => {
271
+ throw new CommanderError(1, 'VSTORAGE_FAILURE', err.message);
272
+ });
273
+ // XXX runtime shape-check
274
+ const questionDesc = /** @type {any} */ (info);
275
+
276
+ // TODO support multiple position arguments
277
+ const chosenPositions = [questionDesc.positions[opts.forPosition]];
278
+ assert(chosenPositions, `undefined position index ${opts.forPosition}`);
279
+
280
+ /** @type {Parameters<typeof processOffer>[0]['toOffer']} */
281
+ const toOffer = (agoricNames, current) => {
282
+ const cont = current ? findContinuingIds(current, agoricNames) : [];
283
+ const votingRight = cont.find(
284
+ it => it.instance === agoricNames.instance.economicCommittee,
285
+ );
286
+ if (!votingRight) {
287
+ console.debug('continuing ids', cont, 'for', current);
288
+ throw new CommanderError(
289
+ 1,
290
+ 'NO_INVITATION',
291
+ 'first, try: agops ec committee ...',
292
+ );
293
+ }
294
+ return {
295
+ id: opts.offerId,
296
+ invitationSpec: {
297
+ source: 'continuing',
298
+ previousOffer: votingRight.offerId,
299
+ invitationMakerName: 'makeVoteInvitation',
300
+ // (positionList, questionHandle)
301
+ invitationArgs: harden([
302
+ chosenPositions,
303
+ questionDesc.questionHandle,
304
+ ]),
305
+ },
306
+ proposal: {},
307
+ };
308
+ };
309
+
310
+ await processOffer({ toOffer, sendFrom: opts.sendFrom }, utils);
311
+ });
312
+
313
+ return ec;
314
+ };