-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcli.ts
More file actions
566 lines (518 loc) · 22.5 KB
/
cli.ts
File metadata and controls
566 lines (518 loc) · 22.5 KB
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
import { Command } from 'commander';
import { Commands } from './commands.js';
import { JsonRpcProvider, Signer, ethers } from 'ethers';
import chalk from 'chalk';
import { stdin as input, stdout as output } from 'node:process';
import { createInterface } from 'readline/promises';
import { unitsToAmount } from '@oceanprotocol/lib';
import { toBoolean } from './helpers.js';
async function initializeSigner() {
const provider = new JsonRpcProvider(process.env.RPC);
let signer: Signer;
if (process.env.PRIVATE_KEY) {
signer = new ethers.Wallet(process.env.PRIVATE_KEY, provider);
} else {
signer = ethers.Wallet.fromPhrase(process.env.MNEMONIC, provider);
}
const { chainId } = await signer.provider.getNetwork();
return { signer, chainId: Number(chainId) };
}
export async function createCLI() {
if (!process.env.MNEMONIC && !process.env.PRIVATE_KEY) {
console.error(chalk.red("Have you forgot to set MNEMONIC or PRIVATE_KEY?"));
process.exit(1);
}
if (!process.env.RPC) {
console.error(chalk.red("Have you forgot to set env RPC?"));
process.exit(1);
}
if (!process.env.NODE_URL) {
console.error(chalk.red("Have you forgot to set env NODE_URL?"));
process.exit(1);
}
const program = new Command();
program
.name('ocean-cli')
.description('CLI tool to interact with Ocean Protocol')
.version('2.0.0')
.helpOption('-h, --help', 'Display help for command');
// Custom help command to support legacy "h" invocation.
// Note: We use console.log(program.helpInformation()) to print the full help output.
program
.command('help')
.alias('h')
.description('Display help for all commands')
.action(() => {
console.log(program.helpInformation());
});
// getDDO command
program
.command('getDDO')
.description('Gets DDO for an asset using the asset did')
.argument('<did>', 'The asset DID')
.option('-d, --did <did>', 'The asset DID')
.action(async (did, options) => {
const assetDid = options.did || did;
if (!assetDid) {
console.error(chalk.red('DID is required'));
// process.exit(1);
return
}
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
await commands.getDDO([null, assetDid]);
});
// publish command
program
.command('publish')
.description('Publishes a new asset with access service or compute service')
.argument('<metadataFile>', 'Path to metadata file')
.option('-f, --file <metadataFile>', 'Path to metadata file')
.option('-e, --encrypt [boolean]', 'Encrypt DDO', true)
.action(async (metadataFile, options) => {
const file = options.file || metadataFile;
if (!file) {
console.error(chalk.red('Metadata file is required'));
// process.exit(1);
return
}
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
await commands.publish([null, file, options.encrypt.toString()]);
});
// publishAlgo command
program
.command('publishAlgo')
.description('Publishes a new algorithm')
.argument('<metadataFile>', 'Path to metadata file')
.option('-f, --file <metadataFile>', 'Path to metadata file')
.option('-e, --encrypt [boolean]', 'Encrypt DDO', true)
.action(async (metadataFile, options) => {
const file = options.file || metadataFile;
if (!file) {
console.error(chalk.red('Metadata file is required'));
// process.exit(1);
return
}
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
await commands.publishAlgo([null, file, options.encrypt.toString()]);
});
// editAsset command (alias "edit" for backwards compatibility)
program
.command('editAsset')
.alias('edit')
.description('Updates DDO using the metadata items in the file')
.argument('<datasetDid>', 'Dataset DID')
.argument('<metadataFile>', 'Updated metadata file')
.option('-d, --did <datasetDid>', 'Dataset DID')
.option('-f, --file <metadataFile>', 'Updated metadata file')
.option('-e, --encrypt [boolean]', 'Encrypt DDO', true)
.action(async (datasetDid, metadataFile, options) => {
const dsDid = options.did || datasetDid;
const file = options.file || metadataFile;
if (!dsDid || !file) {
console.error(chalk.red('Dataset DID and metadata file are required'));
// process.exit(1);
return
}
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
await commands.editAsset([null, dsDid, file, options.encrypt.toString()]);
});
// download command
program
.command('download')
.description('Downloads an asset into specified folder')
.argument('<did>', 'The asset DID')
.argument('[folder]', 'Destination folder', '.')
.option('-d, --did <did>', 'The asset DID')
.option('-f, --folder [folder]', 'Destination folder', '.')
.action(async (did, folder, options) => {
const assetDid = options.did || did;
const destFolder = options.folder || folder || '.';
if (!assetDid) {
console.error(chalk.red('DID is required'));
// process.exit(1);
return
}
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
await commands.download([null, assetDid, destFolder]);
});
// allowAlgo command
program
.command('allowAlgo')
.description('Approves an algorithm to run on a dataset')
.argument('<datasetDid>', 'Dataset DID')
.argument('<algoDid>', 'Algorithm DID')
.option('-d, --dataset <datasetDid>', 'Dataset DID')
.option('-a, --algo <algoDid>', 'Algorithm DID')
.option('-e, --encrypt [boolean]', 'Encrypt DDO', true)
.action(async (datasetDid, algoDid, options) => {
const dsDid = options.dataset || datasetDid;
const aDid = options.algo || algoDid;
if (!dsDid || !aDid) {
console.error(chalk.red('Dataset DID and Algorithm DID are required'));
// process.exit(1);
return
}
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
await commands.allowAlgo([null, dsDid, aDid, options.encrypt.toString()]);
});
// startCompute command
program
.command('startCompute')
.description('Starts a compute job')
.argument('<datasetDids>', 'Dataset DIDs (comma-separated) OR (empty array for none)')
.argument('<algoDid>', 'Algorithm DID')
.argument('<computeEnvId>', 'Compute environment ID')
.argument('<maxJobDuration>', 'maxJobDuration for compute job')
.argument('<paymentToken>', 'Payment token for compute')
.argument('<resources>', 'Resources of compute environment stringified')
.option('-d, --datasets <datasetDids>', 'Dataset DIDs (comma-separated) OR (empty array for none)')
.option('-a, --algo <algoDid>', 'Algorithm DID')
.option('-e, --env <computeEnvId>', 'Compute environment ID')
.option('--maxJobDuration <maxJobDuration>', 'Compute maxJobDuration')
.option('-t, --token <paymentToken>', 'Compute payment token')
.option('--resources <resources>', 'Compute resources')
.option('--accept [boolean]', 'Auto-confirm payment for compute job (true/false)', toBoolean)
.action(async (datasetDids, algoDid, computeEnvId, maxJobDuration, paymentToken, resources, options) => {
const dsDids = options.datasets || datasetDids;
const aDid = options.algo || algoDid;
const envId = options.env || computeEnvId;
const jobDuration = options.maxJobDuration || maxJobDuration;
const token = options.token || paymentToken;
const res = options.resources || resources;
if (!dsDids || !aDid || !envId || !jobDuration || !token || !res) {
console.error(chalk.red('Missing required arguments'));
// process.exit(1);
return
}
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
const initArgs = [null, dsDids, aDid, envId, jobDuration, token, res];
const initResp = await commands.initializeCompute(initArgs);
if (!initResp) {
console.error(chalk.red('Initialization failed. Aborting.'));
return;
}
console.log(chalk.yellow('\n--- Payment Details ---'));
console.log(JSON.stringify(initResp, null, 2));
const amount = await unitsToAmount(signer, initResp.payment.token, initResp.payment.amount.toString());
const proceed = options.accept;
if (!proceed) {
if (!process.stdin.isTTY) {
console.error(chalk.red('Cannot prompt for confirmation (non-TTY). Use "--accept true" to skip.'));
process.exit(1);
}
const rl = createInterface({ input, output });
const confirmation = await rl.question(`\nProceed with payment for starting compute job at price ${amount} in tokens from address ${initResp.payment.token}? (y/n): `);
rl.close();
if (confirmation.toLowerCase() !== 'y' && confirmation.toLowerCase() !== 'yes') {
console.log(chalk.red('Compute job canceled by user.'));
return;
}
} else {
console.log(chalk.cyan('Auto-confirm enabled with --yes flag.'));
}
const computeArgs = [null, dsDids, aDid, envId, JSON.stringify(initResp), jobDuration, token, res];
await commands.computeStart(computeArgs);
console.log(chalk.green('Compute job started successfully.'));
});
// startFreeCompute command
program
.command('startFreeCompute')
.description('Starts a FREE compute job')
.argument('<datasetDids>', 'Dataset DIDs (comma-separated) OR (empty array for none)')
.argument('<algoDid>', 'Algorithm DID')
.argument('<computeEnvId>', 'Compute environment ID')
.option('-d, --datasets <datasetDids>', 'Dataset DIDs (comma-separated) OR (empty array for none)')
.option('-a, --algo <algoDid>', 'Algorithm DID')
.option('-e, --env <computeEnvId>', 'Compute environment ID')
.action(async (datasetDids, algoDid, computeEnvId, options) => {
const dsDids = options.datasets || datasetDids;
const aDid = options.algo || algoDid;
const envId = options.env || computeEnvId;
if (!dsDids || !aDid || !envId) {
console.error(chalk.red('Missing required arguments'));
// process.exit(1);
return
}
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
await commands.freeComputeStart([null, dsDids, aDid, envId]);
});
// getComputeEnvironments command
program
.command('getComputeEnvironments')
.alias('getC2DEnvs')
.description('Gets the existing compute environments')
.action(async () => {
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
await commands.getComputeEnvironments();
});
// startFreeCompute command
program
.command('computeStreamableLogs')
.description('Gets the existing compute streamable logs')
.argument('<jobId>', 'Job ID')
.option('-j, --job <jobId>', 'Job ID')
.action(async (jobId, options) => {
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
const args = jobId || options.job
await commands.computeStreamableLogs([args]);
});
// stopCompute command
program
.command('stopCompute')
.description('Stops a compute job')
.argument('<datasetDid>', 'Dataset DID')
.argument('<jobId>', 'Job ID')
.argument('<agreementId>', 'Agreement ID')
.option('-d, --dataset <datasetDid>', 'Dataset DID')
.option('-j, --job <jobId>', 'Job ID')
.option('-a, --agreement [agreementId]', 'Agreement ID')
.action(async (datasetDid, jobId, agreementId, options) => {
const dsDid = options.dataset || datasetDid;
const jId = options.job || jobId;
const agrId = options.agreement || agreementId;
if (!dsDid || !jId) {
console.error(chalk.red('Dataset DID and Job ID are required'));
// process.exit(1);
return
}
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
const args = [null, dsDid, jId];
if (agrId) args.push(agrId);
await commands.computeStop(args);
});
// getJobStatus command
program
.command('getJobStatus')
.description('Displays the compute job status')
.argument('<datasetDid>', 'Dataset DID')
.argument('<jobId>', 'Job ID')
.argument('<agreementId>', 'Agreement ID')
.option('-d, --dataset <datasetDid>', 'Dataset DID')
.option('-j, --job <jobId>', 'Job ID')
.option('-a, --agreement [agreementId]', 'Agreement ID')
.action(async (datasetDid, jobId, agreementId, options) => {
const dsDid = options.dataset || datasetDid;
const jId = options.job || jobId;
const agrId = options.agreement || agreementId;
if (!dsDid || !jId) {
console.error(chalk.red('Dataset DID and Job ID are required'));
// process.exit(1);
return
}
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
const args = [null, dsDid, jId];
if (agrId) args.push(agrId);
await commands.getJobStatus(args);
});
// downloadJobResults command
program
.command('downloadJobResults')
.description('Downloads compute job results')
.argument('<jobId>', 'Job ID')
.argument('<resultIndex>', 'Result index', parseInt)
.argument('[destinationFolder]', 'Destination folder', '.')
.action(async (jobId, resultIndex, destinationFolder) => {
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
await commands.downloadJobResults([null, jobId, resultIndex, destinationFolder]);
});
// mintOcean command
program
.command('mintOcean')
.description('Mints Ocean tokens')
.action(async () => {
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
await commands.mintOceanTokens();
});
// Generate new auth token
program
.command('generateAuthToken')
.description('Generate new auth token')
.action(async () => {
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
await commands.generateAuthToken();
});
// Invalidate auth token
program
.command('invalidateAuthToken')
.description('Invalidate auth token')
.argument('<token>', 'Auth token')
.option('-t, --token <token>', 'Auth token')
.action(async (token, options) => {
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
await commands.invalidateAuthToken([token || options.token]);
});
// Escrow deposit command
program
.command('depositEscrow')
.description('Deposit tokens into the escrow contract')
.argument('<token>', 'Address of the token to deposit')
.argument('<amount>', 'Amount of tokens to deposit')
.option('-t, --token <token>', 'Address of the token to deposit')
.option('-a, --amount <amount>', 'Amount of tokens to deposit')
.action(async (token, amount, options) => {
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
const tokenAddress = options.token || token;
const amountToDeposit = options.amount || amount;
const success = await commands.depositToEscrow(signer, tokenAddress, amountToDeposit, chainId);
if (!success) {
console.log(chalk.red('Deposit failed'));
return;
}
console.log(chalk.green('Deposit successful'));
});
// Check escrow deposited balance
program
.command('getUserFundsEscrow')
.description('Get deposited token amount in escrow for user')
.argument('<token>', 'Address of the token to check')
.option('-t, --token <token>', 'Address of the token to check')
.action(async (token, options) => {
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
await commands.getEscrowBalance(token || options.token);
});
// Withdraw from escrow
program
.command('withdrawFromEscrow')
.description('Withdraw tokens from escrow')
.argument('<token>', 'Address of the token to check')
.argument('<amount>', 'Amount of tokens to withdraw')
.option('-t, --token <token>', 'Address of the token to check')
.option('-a, --amount <amount>', 'Amount of tokens to withdraw')
.action(async (token, amount, options) => {
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
await commands.withdrawFromEscrow(token || options.token, amount);
});
// Escrow authorization command
program
.command('authorizeEscrow')
.description('Authorize a payee to lock and claim funds from escrow')
.argument('<token>', 'Address of the token to authorize')
.argument('<payee>', 'Address of the payee to authorize')
.argument('<maxLockedAmount>', 'Maximum amount that can be locked by payee')
.argument('<maxLockSeconds>', 'Maximum lock duration in seconds')
.argument('<maxLockCounts>', 'Maximum number of locks allowed')
.option('-t, --token <token>', 'Address of the token to authorize')
.option('-p, --payee <payee>', 'Address of the payee to authorize')
.option('-m, --maxLockedAmount <maxLockedAmount>', 'Maximum amount that can be locked by payee')
.option('-s, --maxLockSeconds <maxLockSeconds>', 'Maximum lock duration in seconds')
.option('-c, --maxLockCounts <maxLockCounts>', 'Maximum number of locks allowed')
.action(async (token, payee, maxLockedAmount, maxLockSeconds, maxLockCounts, options) => {
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
const tokenAddress = options.token || token;
const payeeAddress = options.payee || payee;
const maxLockedAmountValue = options.maxLockedAmount || maxLockedAmount;
const maxLockSecondsValue = options.maxLockSeconds || maxLockSeconds;
const maxLockCountsValue = options.maxLockCounts || maxLockCounts;
const success = await commands.authorizeEscrowPayee(
tokenAddress,
payeeAddress,
maxLockedAmountValue,
maxLockSecondsValue,
maxLockCountsValue,
);
if (!success) {
console.log(chalk.red('Authorization failed'));
return;
}
console.log(chalk.green('Authorization successful'));
});
program
.command('getAuthorizationsEscrow')
.description('Get authorizations for escrow')
.argument('<token>', 'Address of the token to check')
.argument('<payee>', 'Address of the payee to check')
.option('-t, --token <token>', 'Address of the token to check')
.option('-p, --payee <payee>', 'Address of the payee to check')
.action(async (token, payee, options) => {
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
await commands.getAuthorizationsEscrow(token || options.token, payee || options.payee);
});
program
.command('createAccessList')
.description('Create a new access list contract')
.argument('<name>', 'Name for the access list')
.argument('<symbol>', 'Symbol for the access list')
.argument('[transferable]', 'Whether tokens are transferable (true/false)', 'false')
.argument('[initialUsers]', 'Comma-separated list of initial user addresses', '')
.option('-n, --name <name>', 'Name for the access list')
.option('-s, --symbol <symbol>', 'Symbol for the access list')
.option('-t, --transferable [transferable]', 'Whether tokens are transferable (true/false)', 'false')
.option('-u, --users [initialUsers]', 'Comma-separated list of initial user addresses', '')
.action(async (name, symbol, transferable, initialUsers, options) => {
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
await commands.createAccessList([
options.name || name,
options.symbol || symbol,
options.transferable || transferable,
options.users || initialUsers
]);
});
program
.command('addToAccessList')
.description('Add user(s) to an access list')
.argument('<accessListAddress>', 'Address of the access list contract')
.argument('<users>', 'Comma-separated list of user addresses to add')
.option('-a, --address <accessListAddress>', 'Address of the access list contract')
.option('-u, --users <users>', 'Comma-separated list of user addresses to add')
.action(async (accessListAddress, users, options) => {
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
await commands.addToAccessList([
options.address || accessListAddress,
options.users || users
]);
});
program
.command('checkAccessList')
.description('Check if user(s) are on an access list')
.argument('<accessListAddress>', 'Address of the access list contract')
.argument('<users>', 'Comma-separated list of user addresses to check')
.option('-a, --address <accessListAddress>', 'Address of the access list contract')
.option('-u, --users <users>', 'Comma-separated list of user addresses to check')
.action(async (accessListAddress, users, options) => {
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
await commands.checkAccessList([
options.address || accessListAddress,
options.users || users
]);
});
program
.command('removeFromAccessList')
.description('Remove user(s) from an access list')
.argument('<accessListAddress>', 'Address of the access list contract')
.argument('<users>', 'Comma-separated list of user addresses to remove')
.option('-a, --address <accessListAddress>', 'Address of the access list contract')
.option('-u, --users <users>', 'Comma-separated list of user addresses to remove')
.action(async (accessListAddress, users, options) => {
const { signer, chainId } = await initializeSigner();
const commands = new Commands(signer, chainId);
await commands.removeFromAccessList([
options.address || accessListAddress,
options.users || users
]);
});
return program;
}