Repository navigation
Expand file tree
/
Copy pathcli.ts
More file actions
1785 lines (1641 loc) · 58 KB
/
Copy pathcli.ts
File metadata and controls
1785 lines (1641 loc) · 58 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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
import { Address, StrKey } from '@stellar/stellar-sdk';
import { Command } from 'commander';
import pc from 'picocolors';
import fs from 'node:fs';
import { parseDisplayAmount } from './amounts';
import { ILNClient } from './client';
import { loadConfig, initConfig, readRawConfig, writeRawConfig } from './config';
import { parseDueDate } from './dates';
import { LocalDevEnvironment } from './dev-environment';
import { formatUnknownError, formatILNError, isStructuredError } from './errors';
import { decodeScValXdr, formatDecodedScVal } from './xdr';
import {
createUi,
describeConfig,
formatHistoryJson,
formatHistoryTable,
formatInvoiceDetails,
formatInvoiceDetailsJson,
formatInvoiceList,
formatInvoiceListJson,
formatProtocolConfig,
formatProtocolConfigJson,
formatProtocolStats,
formatProtocolStatsJson,
formatReputation,
formatReputationJson,
helpExample,
helpSection,
formatJsonSuccess,
formatJsonError,
} from './format';
import { generateManPage } from './man';
import { registerInspectCommand } from './inspect';
import { registerCompletionCommand } from './completion';
import { registerEnvCommands } from './env';
import {
promptMissingArguments,
validateStellarAddress,
validatePositiveInteger,
validatePositiveNumber,
validateBasisPoints,
validateDate,
} from './prompts';
import { createKeypairFileSigner } from './signer';
import { TestnetAccountSeeder } from './dev-seed';
import {
createWallet,
importWallet,
listWallets,
deleteWallet,
fundWalletFromFriendbot,
} from './wallet';
import type { Ui } from './format';
import type { Invoice, ResolvedConfig } from './types';
import { checkCompatibility } from '@iln/sdk';
import { runInteractive } from './interactive';
import { VersionManager } from './version';
import { runTutorial } from './tutorial';
import { withSpinner, createTransactionProgress, type ProgressOptions } from './progress';
export interface CliDependencies {
createClient(config: ResolvedConfig): ILNClient;
createDevEnvironment?(ui: Ui): Pick<LocalDevEnvironment, 'reset' | 'start' | 'status' | 'stop'>;
loadConfig(options?: { cwd?: string; env?: NodeJS.ProcessEnv }): ResolvedConfig;
stderr: NodeJS.WritableStream;
stdout: NodeJS.WritableStream;
__returnProgramForDocs?: boolean;
}
export async function runCli(
argv: string[],
dependencies: Partial<CliDependencies> = {}
): Promise<number | any> {
const stdout = dependencies.stdout ?? process.stdout;
const stderr = dependencies.stderr ?? process.stderr;
const ui = createUi(stdout, stderr);
const load = dependencies.loadConfig ?? loadConfig;
const createClient =
dependencies.createClient ??
((config: ResolvedConfig) =>
new ILNClient({
contractId: config.contractId,
networkPassphrase: config.networkPassphrase,
rpcUrl: config.rpcUrl,
signer: createKeypairFileSigner(config.keypairPath),
}));
const createDevEnvironment =
dependencies.createDevEnvironment ?? ((devUi: Ui) => new LocalDevEnvironment({ ui: devUi }));
// Step 1: Load custom aliases from config
let customAliases: Record<string, string> = {};
try {
const { rawConfig } = readRawConfig(process.cwd());
customAliases = rawConfig.aliases || {};
} catch {
// Ignore if config doesn't exist or is invalid
}
// Step 2: Resolve aliases in argv
const resolvedArgv = [...argv];
if (resolvedArgv.length > 0) {
const firstArg = resolvedArgv[0];
if (customAliases[firstArg]) {
resolvedArgv[0] = customAliases[firstArg];
}
}
const program = new Command();
program.configureOutput({
writeOut: (str) => stdout.write(str),
writeErr: (str) => stderr.write(str),
});
program.configureHelp({
formatHelp: (cmd, helper) => {
const term = (str: string) => pc.bold(pc.cyan(str));
const sections: string[] = [];
const usage = helper.commandUsage(cmd);
if (usage) sections.push(`${pc.bold('Usage:')} ${usage}`);
const description = helper.commandDescription(cmd);
if (description) sections.push(`\n${description}`);
const args = helper.visibleArguments(cmd);
if (args.length) {
sections.push(`\n${pc.bold('Arguments:')}`);
args.forEach((a) =>
sections.push(
` ${term(
helper.argumentTerm(a).padEnd(helper.padWidth(cmd, helper))
)} ${helper.argumentDescription(a)}`
)
);
}
const opts = helper.visibleOptions(cmd);
if (opts.length) {
sections.push(`\n${pc.bold('Options:')}`);
opts.forEach((o) =>
sections.push(
` ${term(
helper.optionTerm(o).padEnd(helper.padWidth(cmd, helper))
)} ${helper.optionDescription(o)}`
)
);
}
const cmds = helper.visibleCommands(cmd);
if (cmds.length) {
sections.push(`\n${pc.bold('Commands:')}`);
cmds.forEach((c) =>
sections.push(
` ${term(
helper.subcommandTerm(c).padEnd(helper.padWidth(cmd, helper))
)} ${helper.subcommandDescription(c)}`
)
);
}
return sections.join('\n') + '\n';
},
});
const versionManager = new VersionManager(ui);
program
.name('iln')
.version(versionManager.getCurrentVersion(), '-v, --version', 'output the current version')
.description('Invoice Liquidity Network CLI')
.exitOverride()
.showHelpAfterError()
.option('--json', 'output machine-readable JSON (applies to: status, list)')
.option('--quiet', 'suppress informational messages; show only command output')
.hook('preAction', (_thisCommand, actionCommand) => {
registerCompletionCommand(program);
registerEnvCommands(program);
registerInspectCommand(program, createClient, load, ui);
const isConfiglessXdrCommand =
actionCommand.name() === 'decode' && actionCommand.parent?.name() === 'xdr';
if (
actionCommand.name() === 'man' ||
isConfiglessXdrCommand ||
(actionCommand.parent?.name() === 'dev' &&
['reset', 'start', 'status', 'stop'].includes(actionCommand.name()))
) {
return;
}
const config = load();
const opts = program.opts() as { json?: boolean; quiet?: boolean };
if (!opts.quiet && !opts.json) {
ui.info(`Using ${describeConfig(config)}`);
}
// --- Version Management ---
const currentVersion = versionManager.getCurrentVersion();
// 1. Version Pinning
if (config.requiredVersion && config.requiredVersion !== currentVersion) {
throw new Error(
`Version mismatch: This project requires ILN CLI version ${config.requiredVersion}, but you are running ${currentVersion}.`
);
}
// 2. Update Check
if (config.autoUpdate && !opts.quiet && !opts.json) {
// Fire and forget update check to not block startup significantly
void versionManager.notifyUpdateIfAvailable();
}
});
program
.command('submit')
.alias('s')
.description('Submit a new invoice from the configured signer account.')
.option('--payer <address>', 'payer Stellar address')
.option('--amount <amount>', 'invoice amount in display units, for example 100 or 12.5')
.option('--due <date>', 'due date as YYYY-MM-DD or Unix timestamp')
.option('--rate <bps>', 'discount rate in basis points')
.option('--token <contractId>', 'override token contract ID from config')
.option('--yes', 'skip interactive prompts and use defaults')
.addHelpText(
'after',
[
'',
helpSection('Examples:'),
helpExample('iln submit --payer GABC... --amount 100 --due 2026-03-31 --rate 300'),
helpExample(
'iln submit --payer GABC... --amount 12.5 --due 2026-06-15 --rate 150 --token CDEF...'
),
'',
helpSection('See also:'),
helpExample('iln status --id <id> Check the state of a submitted invoice'),
helpExample('iln list --address <G> List all invoices for your address'),
].join('\n')
)
.action(
async (options: {
amount?: string;
due?: string;
payer?: string;
rate?: string;
token?: string;
yes?: boolean;
}) => {
const config = load();
const client = createClient(config);
const tokenId = options.token ?? config.tokenId;
if (!tokenId) {
throw new Error(
'Missing token ID. Set `tokenId` in .iln.json, set `ILN_TOKEN_ID`, or pass `--token`.'
);
}
// Prompt for missing required arguments in interactive mode
let payer = options.payer;
let amount = options.amount;
let due = options.due;
let rate = options.rate;
if (!options.yes && process.stdin.isTTY) {
const resolved = await promptMissingArguments(
[
{
name: 'payer',
description: 'Payer Stellar address (G...)',
required: true,
validate: validateStellarAddress,
},
{
name: 'amount',
description: 'Invoice amount in display units (e.g. 100 or 12.5)',
required: true,
validate: validatePositiveNumber,
},
{
name: 'due',
description: 'Due date as YYYY-MM-DD or Unix timestamp',
required: true,
validate: validateDate,
},
{
name: 'rate',
description: 'Discount rate in basis points (e.g. 500 = 5%)',
required: true,
defaultValue: '500',
validate: validateBasisPoints,
},
],
{ payer, amount, due, rate }
);
payer = resolved.payer;
amount = resolved.amount;
due = resolved.due;
rate = resolved.rate;
}
if (!payer || !amount || !due || !rate) {
throw new Error(
'Missing required arguments. Use --payer, --amount, --due, --rate or run interactively.'
);
}
assertStellarAddress(payer, 'payer');
assertContractId(tokenId, 'token');
const progress = cliProgressOptions(program, stdout);
const tx = createTransactionProgress('Submitting invoice', progress);
let submitResult: { invoiceId: bigint; txHash: string };
try {
submitResult = await client.submitInvoice({
amount: parseDisplayAmount(amount),
discountRate: parseBasisPoints(rate),
dueDate: parseDueDate(due),
payer,
tokenId,
});
tx.succeed(
`Invoice ${submitResult.invoiceId.toString()} submitted (tx ${submitResult.txHash})`
);
} catch (err) {
tx.fail('Invoice submission failed');
throw err;
}
const globalOpts = program.opts() as { json?: boolean };
if (globalOpts.json) {
stdout.write(
formatJsonSuccess({
invoiceId: submitResult.invoiceId.toString(),
txHash: submitResult.txHash,
}) + '\n'
);
}
}
);
program
.command('fund')
.alias('f')
.description('Fund an invoice using the configured signer account.')
.option('--id <invoiceId>', 'invoice ID')
.option(
'--amount <amount>',
'amount to fund in display units; defaults to the remaining balance'
)
.option('--yes', 'skip interactive prompts and use defaults')
.addHelpText(
'after',
[
'',
helpSection('Examples:'),
helpExample('iln fund --id 42'),
helpExample('iln fund --id 42 --amount 50 (partial funding)'),
'',
helpSection('See also:'),
helpExample('iln status --id <id> Confirm the invoice is now Funded'),
helpExample('iln history --address <G> View your funding history'),
].join('\n')
)
.action(async (options: { amount?: string; id?: string; yes?: boolean }) => {
let invoiceId = await resolveIdFromStdin(options.id);
if (!invoiceId && !options.yes && process.stdin.isTTY) {
const resolved = await promptMissingArguments(
[
{
name: 'id',
description: 'Invoice ID to fund',
required: true,
validate: validatePositiveInteger,
},
],
{ id: invoiceId }
);
invoiceId = resolved.id;
}
if (!invoiceId) {
throw new Error('Missing required argument: --id. Provide it via option or pipe to stdin.');
}
const client = createClient(load());
const progress = cliProgressOptions(program, stdout);
const tx = createTransactionProgress('Funding invoice', progress);
let fundResult: { hash: string };
try {
fundResult = await client.fundInvoice(
parseInvoiceId(invoiceId),
options.amount ? parseDisplayAmount(options.amount) : undefined
);
tx.succeed(`Invoice ${invoiceId} funded (tx ${fundResult.hash})`);
} catch (err) {
tx.fail('Invoice funding failed');
throw err;
}
const globalOpts = program.opts() as { json?: boolean };
if (globalOpts.json) {
stdout.write(
formatJsonSuccess({ invoiceId: invoiceId.toString(), txHash: fundResult.hash }) + '\n'
);
}
});
program
.command('pay')
.alias('p')
.description('Mark an invoice as paid using the configured signer account.')
.option('--id <invoiceId>', 'invoice ID')
.option('--yes', 'skip interactive prompts and use defaults')
.addHelpText(
'after',
[
'',
helpSection('Examples:'),
helpExample('iln pay --id 42'),
'',
helpSection('Tips:'),
helpExample('Only the payer address on the invoice can mark it paid.'),
helpExample('Run `iln status --id <id>` first to confirm the invoice is Funded.'),
'',
helpSection('See also:'),
helpExample('iln status --id <id> Verify the invoice is now Paid'),
helpExample('iln history --address <G> View your payment history'),
].join('\n')
)
.action(async (options: { id?: string; yes?: boolean }) => {
let invoiceId = await resolveIdFromStdin(options.id);
if (!invoiceId && !options.yes && process.stdin.isTTY) {
const resolved = await promptMissingArguments(
[
{
name: 'id',
description: 'Invoice ID to mark as paid',
required: true,
validate: validatePositiveInteger,
},
],
{ id: invoiceId }
);
invoiceId = resolved.id;
}
if (!invoiceId) {
throw new Error('Missing required argument: --id. Provide it via option or pipe to stdin.');
}
const client = createClient(load());
const progress = cliProgressOptions(program, stdout);
const tx = createTransactionProgress('Marking invoice paid', progress);
let payResult: { hash: string };
try {
payResult = await client.markPaid(parseInvoiceId(invoiceId));
tx.succeed(`Invoice ${invoiceId} marked paid (tx ${payResult.hash})`);
} catch (err) {
tx.fail('Mark-paid failed');
throw err;
}
const globalOpts = program.opts() as { json?: boolean };
if (globalOpts.json) {
stdout.write(
formatJsonSuccess({ invoiceId: invoiceId.toString(), txHash: payResult.hash }) + '\n'
);
}
});
program
.command('status')
.description('Show the current state of an invoice.')
.option('--id <invoiceId>', 'invoice ID')
.option('--yes', 'skip interactive prompts and use defaults')
.addHelpText(
'after',
[
'',
helpSection('Examples:'),
helpExample('iln status --id 42'),
helpExample('iln status --id 1 (invoice IDs start at 1)'),
'',
helpSection('See also:'),
helpExample('iln list --address <G> List all invoices for an address'),
helpExample('iln history --address <G> View full action history'),
].join('\n')
)
.action(async (options: { id?: string; yes?: boolean }) => {
let invoiceId = await resolveIdFromStdin(options.id);
if (!invoiceId && !options.yes && process.stdin.isTTY) {
const resolved = await promptMissingArguments(
[
{
name: 'id',
description: 'Invoice ID to check status',
required: true,
validate: validatePositiveInteger,
},
],
{ id: invoiceId }
);
invoiceId = resolved.id;
}
if (!invoiceId) {
throw new Error('Missing required argument: --id. Provide it via option or pipe to stdin.');
}
const client = createClient(load());
const progress = cliProgressOptions(program, stdout);
const invoice = await withSpinner(
'Fetching invoice…',
() => client.getInvoice(parseInvoiceId(invoiceId)),
progress,
`Fetched invoice ${invoiceId}`
);
const opts = program.opts() as { json?: boolean };
ui.info(
opts.json
? formatJsonSuccess(JSON.parse(formatInvoiceDetailsJson(invoice)))
: formatInvoiceDetails(invoice)
);
});
program
.command('list')
.description('List all invoices associated with a Stellar address.')
.option('--address <address>', 'freelancer, payer, or funder Stellar address')
.option('--yes', 'skip interactive prompts and use defaults')
.addHelpText(
'after',
[
'',
helpSection('Examples:'),
helpExample('iln list --address GABC...'),
helpExample(
'iln list --address GABC... (returns invoices where address is freelancer, payer, or funder)'
),
'',
helpSection('See also:'),
helpExample('iln history --address <G> Filter by action type or invoice ID'),
helpExample('iln status --id <id> Inspect a specific invoice'),
].join('\n')
)
.action(async (options: { address?: string; yes?: boolean }) => {
let address = options.address;
if (!options.yes && process.stdin.isTTY) {
const resolved = await promptMissingArguments(
[
{
name: 'address',
description: 'Stellar address to list invoices for',
required: true,
validate: validateStellarAddress,
},
],
{ address }
);
address = resolved.address;
}
if (!address) {
throw new Error('Missing required argument: --address');
}
assertStellarAddress(address, 'address');
const client = createClient(load());
const progress = cliProgressOptions(program, stdout);
const invoices = await withSpinner(
'Fetching invoices…',
() => client.listInvoicesByAddress(address),
progress,
'Invoices loaded'
);
const opts = program.opts() as { json?: boolean };
ui.info(
opts.json
? formatJsonSuccess(JSON.parse(formatInvoiceListJson(invoices)))
: formatInvoiceList(invoices)
);
});
program
.command('history')
.description('Show past invoice submissions, fundings, and payments for a Stellar address.')
.option('--address <address>', 'Stellar address to query history for')
.option('--id <invoiceId>', 'filter to a specific invoice ID')
.option(
'--action <type>',
'filter by action type: submit (freelancer), fund (funder), pay (payer)'
)
.option('--limit <n>', 'maximum number of results to return')
.option('--format <fmt>', 'output format: table (default) or json', 'table')
.option('--yes', 'skip interactive prompts and use defaults')
.addHelpText(
'after',
[
'',
helpSection('Examples:'),
helpExample('iln history --address GABC...'),
helpExample('iln history --address GABC... --action fund --limit 10 --format json'),
'',
helpSection('See also:'),
helpExample('iln list --address <G> Quick overview of all invoices'),
helpExample('iln status --id <id> Full details on a single invoice'),
].join('\n')
)
.action(
async (options: {
address?: string;
id?: string;
action?: string;
limit?: string;
format: string;
yes?: boolean;
}) => {
let address = options.address;
if (!options.yes && process.stdin.isTTY) {
const resolved = await promptMissingArguments(
[
{
name: 'address',
description: 'Stellar address to query history for',
required: true,
validate: validateStellarAddress,
},
],
{ address }
);
address = resolved.address;
}
if (!address) {
throw new Error('Missing required argument: --address');
}
assertStellarAddress(address, 'address');
if (options.format !== 'table' && options.format !== 'json') {
throw new Error('--format must be table or json');
}
const ACTION_TO_ROLE: Record<string, 'freelancer' | 'funder' | 'payer'> = {
submit: 'freelancer',
fund: 'funder',
pay: 'payer',
};
if (options.action && !ACTION_TO_ROLE[options.action]) {
throw new Error(`--action must be one of: ${Object.keys(ACTION_TO_ROLE).join(', ')}`);
}
const client = createClient(load());
const progress = cliProgressOptions(program, stdout);
let invoices = await withSpinner(
'Fetching invoice history…',
() => client.listInvoicesByAddress(address),
progress,
'History loaded'
);
if (options.id !== undefined) {
const targetId = parseInvoiceId(options.id);
invoices = invoices.filter((inv) => inv.id === targetId);
}
if (options.action) {
const role = ACTION_TO_ROLE[options.action];
invoices = invoices.filter((inv) => inv.role === role);
}
if (options.limit !== undefined) {
const limit = parseInt(options.limit, 10);
if (isNaN(limit) || limit <= 0) {
throw new Error('--limit must be a positive integer');
}
invoices = invoices.slice(0, limit);
}
const globalOpts = program.opts() as { json?: boolean };
const output =
options.format === 'json' || globalOpts.json
? formatJsonSuccess(JSON.parse(formatHistoryJson(invoices)))
: formatHistoryTable(invoices);
ui.info(output);
}
);
program
.command('watch')
.description('Watch an invoice for real-time status updates until it reaches a terminal state.')
.requiredOption('--id <invoiceId>', 'invoice ID')
.option('--interval <ms>', 'poll interval in milliseconds', '3000')
.addHelpText(
'after',
[
'',
helpSection('Examples:'),
helpExample('iln watch --id 42'),
helpExample('iln watch --id 42 --interval 5000'),
'',
helpSection('Tips:'),
helpExample('Exits automatically once the invoice reaches Paid, Defaulted, or Disputed.'),
helpExample('Press Ctrl-C to stop watching early.'),
'',
helpSection('See also:'),
helpExample('iln status --id <id> One-shot status check'),
].join('\n')
)
.action(async (options: { id: string; interval: string }) => {
const invoiceId = parseInvoiceId(options.id);
const intervalMs = Math.max(1000, parseInt(options.interval, 10) || 3000);
const client = createClient(load());
const globalOpts = program.opts() as { json?: boolean; quiet?: boolean };
const TERMINAL = new Set(['Paid', 'Defaulted', 'Disputed']);
let lastStatus: string | undefined;
const print = (invoice: Invoice) => {
const ts = new Date().toISOString();
if (globalOpts.json) {
stdout.write(
JSON.stringify({ ts, invoiceId: invoice.id.toString(), status: invoice.status }) + '\n'
);
} else {
ui.info(`[${ts}] Invoice ${invoice.id} — ${invoice.status}`);
}
};
if (!globalOpts.quiet && !globalOpts.json) {
ui.info(pc.bold(`Watching invoice ${invoiceId} (Ctrl-C to stop)...`));
}
await new Promise<void>((resolve) => {
let stopped = false;
let timer: ReturnType<typeof setInterval> | undefined;
const finish = () => {
if (stopped) return;
stopped = true;
if (timer) clearInterval(timer);
process.off('SIGINT', onSigint);
resolve();
};
const onSigint = () => {
if (!globalOpts.quiet && !globalOpts.json) {
ui.info('\nStopped watching.');
}
finish();
};
const poll = async () => {
try {
const invoice = await client.getInvoice(invoiceId);
if (invoice.status !== lastStatus) {
print(invoice);
lastStatus = invoice.status;
}
if (TERMINAL.has(invoice.status)) {
if (!globalOpts.json) {
ui.success(`Invoice reached terminal state: ${invoice.status}`);
}
finish();
}
} catch (err: any) {
ui.error(err?.message ?? String(err));
}
};
process.on('SIGINT', onSigint);
void poll().then(() => {
if (!stopped) {
timer = setInterval(poll, intervalMs);
}
});
});
});
program
.command('export')
.description('Export invoices to CSV.')
.option('--address <address>', 'filter by freelancer, payer, or funder address')
.option('--output <file>', 'output file path; use - for stdout', 'invoices.csv')
.addHelpText(
'after',
[
'',
helpSection('Examples:'),
helpExample('iln export --output invoices.csv'),
helpExample('iln export --address GABC... --output -'),
'',
helpSection('See also:'),
helpExample('iln list --address <G> List invoices without exporting'),
].join('\n')
)
.action(async (options: { address?: string; output: string }) => {
if (options.address) {
assertStellarAddress(options.address, 'address');
}
const client = createClient(load());
const progress = cliProgressOptions(program, stdout);
const invoices = await withSpinner(
'Fetching invoices…',
() => fetchInvoicesForExport(client, options.address),
progress,
'Invoices loaded'
);
const header = 'id,freelancer,payer,amount,discountRate,dueDate,status,funder,fundedAt';
const rows = invoices.map((inv) =>
[
csvCell(inv.id.toString()),
csvCell(inv.freelancer),
csvCell(inv.payer),
csvCell(inv.amount.toString()),
csvCell(inv.discountRate),
csvCell(inv.dueDate),
csvCell(inv.status),
csvCell(inv.funder ?? ''),
csvCell(inv.fundedAt ?? ''),
].join(',')
);
const csv = [header, ...rows].join('\n');
if (options.output === '-') {
stdout.write(csv + '\n');
} else {
fs.writeFileSync(options.output, csv, 'utf8');
ui.success(`Exported ${invoices.length} invoice(s) to ${options.output}`);
}
});
program
.command('stats')
.description('Show protocol-wide analytics: total invoices, funded, paid, and volume.')
.option('--api-url <url>', 'override the analytics API base URL')
.addHelpText(
'after',
[
'',
helpSection('Examples:'),
helpExample('iln stats'),
helpExample('iln stats --api-url https://api.iln.network'),
].join('\n')
)
.action(async (options: { apiUrl?: string }) => {
const config = load();
const { AnalyticsSDK } = await import('@iln/sdk');
const baseUrl =
options.apiUrl ??
(config.network === 'mainnet' ? 'https://api.iln.network' : 'http://localhost:3001');
const api = new AnalyticsSDK(baseUrl);
const progress = cliProgressOptions(program, stdout);
const stats = await withSpinner(
'Fetching protocol stats…',
() => api.getProtocolStats(),
progress,
'Stats loaded'
);
const globalOpts = program.opts() as { json?: boolean };
ui.info(
globalOpts.json
? formatJsonSuccess(JSON.parse(formatProtocolStatsJson(stats)))
: formatProtocolStats(stats)
);
});
// Reputation command
const reputationCommand = program
.command('reputation')
.description('Query on-chain reputation scores.');
reputationCommand
.command('get [address]')
.description(
'Get the reputation score of a Stellar address (defaults to the configured signer).'
)
.addHelpText(
'after',
[
'',
helpSection('Examples:'),
helpExample('iln reputation get GABC...'),
helpExample("iln reputation get (uses the configured signer's address)"),
].join('\n')
)
.action(async (address: string | undefined) => {
const config = load();
const client = createClient(config);
let targetAddress = address;
if (!targetAddress) {
const signer = createKeypairFileSigner(config.keypairPath);
targetAddress = await signer.getPublicKey();
}
assertStellarAddress(targetAddress, 'address');
const progress = cliProgressOptions(program, stdout);
const score = await withSpinner(
'Fetching reputation…',
() => client.getReputation(targetAddress!),
progress,
'Reputation loaded'
);
const globalOpts = program.opts() as { json?: boolean };
ui.info(
globalOpts.json
? formatJsonSuccess(JSON.parse(formatReputationJson(targetAddress, score)))
: formatReputation(targetAddress, score)
);
});
// Network command
const networkCommand = program
.command('network')
.description('Manage the active Stellar network.');
networkCommand
.command('switch <target>')
.description(
'Switch the active network (testnet, mainnet, or standalone) in the local config file.'
)
.addHelpText(
'after',
[
'',
helpSection('Examples:'),
helpExample('iln network switch mainnet'),
helpExample('iln network switch testnet'),
'',
helpSection('Tips:'),
helpExample('Writes to .ilnrc.json, creating it if none exists.'),
helpExample(
"Clears any explicit `rpcUrl` override so the new network's default RPC endpoint applies."
),
'',
helpSection('See also:'),
helpExample('iln config show View the resolved configuration for the current directory'),
].join('\n')
)
.action((target: string) => {
if (target !== 'testnet' && target !== 'mainnet' && target !== 'standalone') {
throw new Error('Unsupported network. Choose one of: "testnet", "mainnet", "standalone".');
}
const cwd = process.cwd();
const { rawConfig } = readRawConfig(cwd);
rawConfig.network = target;
delete rawConfig.rpcUrl;
const filePath = writeRawConfig(cwd, rawConfig);
const globalOpts = program.opts() as { json?: boolean };
if (globalOpts.json) {
stdout.write(formatJsonSuccess({ network: target }) + '\n');
} else {
ui.success(`Active network switched to ${target}.`);
ui.info(`Saved to ${filePath}`);
}
});
// Compatibility check command
const compatCommand = program
.command('compat')
.description('SDK and contract compatibility utilities');
compatCommand
.command('check')
.description('Check SDK compatibility with the deployed contract version.')
.addHelpText(
'after',
[
'',
helpSection('Examples:'),
helpExample('iln compat check'),
'',
helpSection('Tips:'),
helpExample('Run this after updating the SDK or redeploying the contract.'),
helpExample('A failed check means the SDK version does not match the on-chain contract.'),
'',
helpSection('See also:'),
helpExample('iln config Show live protocol parameters from the contract'),
].join('\n')
)
.action(async () => {
const config = load();
const client = createClient(config);