-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathcli-update-asset.js
More file actions
790 lines (681 loc) · 22.5 KB
/
cli-update-asset.js
File metadata and controls
790 lines (681 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
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
#!/usr/bin/env node
/**
* CLI Tool for updating CAIP-19 assets (metadata and images)
*
* Usage:
* node cli-update-asset.js set --caip "eip155:1/erc20:0x..." --name "Token Name" --symbol "TKN" --decimals 18 --image path/to/logo.svg
* node cli-update-asset.js set --caip "eip155:1/erc20:0x..." --name "New Name" --image path/to/new-logo.png
* node cli-update-asset.js verify --caip "eip155:1/erc20:0x..."
* node cli-update-asset.js list --namespace "eip155:1"
*/
const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
const { z } = require('zod');
const https = require('https');
const http = require('http');
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
const copyFile = promisify(fs.copyFile);
const mkdir = promisify(fs.mkdir);
const access = promisify(fs.access);
const readdir = promisify(fs.readdir);
// Parse command line arguments
const args = process.argv.slice(2);
const command = args[0];
// Supported image extensions
const SUPPORTED_IMAGE_EXTENSIONS = ['.svg', '.png', '.jpg', '.jpeg'];
// Zod Schemas
const CAIP19Schema = z.string().regex(
/^[-a-z0-9]{3,8}:[-a-zA-Z0-9]{1,32}\/[-a-z0-9]{3,8}:[a-zA-Z0-9]+$/,
'Invalid CAIP-19 format. Expected: namespace:chainId/assetNamespace:assetReference'
);
const MetadataSchema = z.object({
name: z.string().min(1, "Name is required and cannot be empty"),
symbol: z
.string()
.min(1, "Symbol is required and cannot be empty")
.max(20, "Symbol must be 20 characters or less"),
decimals: z
.number()
.int()
.min(0)
.max(255, "Decimals must be between 0 and 255"),
logo: z.string().min(1, "Logo path is required"),
erc20: z.boolean().optional(),
spl: z.boolean().optional(),
});
const LabelFileSchema = z.object({
labels: z.array(z.string().min(1, "Labels must be non-empty strings")),
});
const SetCommandFlagsSchema = z.object({
caip: z.string(),
name: z.string().optional(),
symbol: z.string().optional(),
decimals: z.string().optional(),
image: z.string().optional(),
labels: z.string().optional(),
erc20: z.enum(["true", "false"]).optional(),
spl: z.enum(["true", "false"]).optional(),
});
const VerifyCommandFlagsSchema = z.object({
caip: z.string()
});
const ListCommandFlagsSchema = z.object({
namespace: z.string().regex(/^[-a-z0-9]{3,8}:[-a-zA-Z0-9]{1,32}$/, 'Invalid namespace format')
});
/**
* Parse CAIP-19 asset identifier
* Format: {namespace}:{chain_id}/{asset_namespace}:{asset_reference}
* Example: eip155:1/erc20:0x6B175474E89094C44Da98b954EedeAC495271d0F
*/
function parseCAIP19(caipId) {
// Validate with Zod
const result = CAIP19Schema.safeParse(caipId);
if (!result.success) {
const errorMessage = result.error.issues[0]?.message || 'Invalid CAIP-19 format';
throw new Error(`${errorMessage}\nExpected format: namespace:chainId/assetNamespace:assetReference\nExample: eip155:1/erc20:0x6B175474E89094C44Da98b954EedeAC495271d0F`);
}
const match = caipId.match(/^([^:]+:[^/]+)\/(.+)$/);
const [, chainNamespace, assetId] = match;
return {
chainNamespace, // e.g., "eip155:1"
assetId, // e.g., "erc20:0x..."
full: caipId
};
}
/**
* Get file paths for metadata and icon
*/
function getAssetPaths(caipId) {
const parsed = parseCAIP19(caipId);
return {
metadataDir: path.join(__dirname, "metadata", parsed.chainNamespace),
metadataFile: path.join(
__dirname,
"metadata",
parsed.chainNamespace,
`${parsed.assetId}.json`,
),
iconDir: path.join(__dirname, "icons", parsed.chainNamespace),
labelsDir: path.join(__dirname, "labels", parsed.chainNamespace),
labelsFile: path.join(
__dirname,
"labels",
parsed.chainNamespace,
`${parsed.assetId}.json`,
),
// We'll determine the actual icon file extension later
iconFileBase: path.join(
__dirname,
"icons",
parsed.chainNamespace,
parsed.assetId,
),
};
}
/**
* Parse labels flag input.
* Supports comma-separated values and JSON arrays.
*/
function parseLabels(labelsInput) {
if (labelsInput === undefined) {
return undefined;
}
const trimmed = labelsInput.trim();
if (!trimmed) {
throw new Error('Labels cannot be empty. Provide a comma-separated list or JSON array.');
}
if (trimmed.startsWith('{')) {
throw new Error('Invalid JSON for --labels: JSON labels input must be an array');
}
let labels;
if (trimmed.startsWith('[')) {
try {
const parsed = JSON.parse(trimmed);
if (!Array.isArray(parsed)) {
throw new Error('JSON labels input must be an array');
}
labels = parsed;
} catch (err) {
throw new Error(`Invalid JSON for --labels: ${err.message}`);
}
} else {
labels = trimmed.split(',').map(label => label.trim()).filter(Boolean);
}
const uniqueLabels = [...new Set(labels)];
const validation = LabelFileSchema.safeParse({ labels: uniqueLabels });
if (!validation.success) {
const errors = validation.error.issues.map(err => err.message).join('; ');
throw new Error(`Invalid --labels value: ${errors}`);
}
return uniqueLabels;
}
/**
* Find existing icon file (any supported extension)
*/
async function findExistingIcon(iconFileBase) {
for (const ext of SUPPORTED_IMAGE_EXTENSIONS) {
const iconPath = `${iconFileBase}${ext}`;
try {
await access(iconPath, fs.constants.F_OK);
return iconPath;
} catch (err) {
// File doesn't exist, continue
}
}
return null;
}
/**
* Check if a string is a URL
*/
function isUrl(str) {
try {
const url = new URL(str);
return url.protocol === 'http:' || url.protocol === 'https:';
} catch {
return false;
}
}
/**
* Download a file from a URL
*/
function downloadFile(url, destPath, redirectCount = 0) {
const MAX_REDIRECTS = 10;
if (redirectCount > MAX_REDIRECTS) {
return Promise.reject(
new Error(
`Too many redirects (>${MAX_REDIRECTS}). Possible redirect loop.`,
),
);
}
return new Promise((resolve, reject) => {
const client = url.startsWith("https") ? https : http;
client
.get(url, (response) => {
// Handle redirects
if (response.statusCode === 301 || response.statusCode === 302) {
downloadFile(response.headers.location, destPath, redirectCount + 1)
.then(resolve)
.catch(reject);
return;
}
if (response.statusCode !== 200) {
reject(new Error(`Failed to download: HTTP ${response.statusCode}`));
return;
}
const fileStream = fs.createWriteStream(destPath);
response.pipe(fileStream);
response.on("error", (err) => {
fs.unlink(destPath, () => {}); // Clean up partial file
reject(err);
});
fileStream.on("finish", () => {
fileStream.close();
resolve(response.headers["content-type"]);
});
fileStream.on("error", (err) => {
fs.unlink(destPath, () => {}); // Clean up partial file
reject(err);
});
})
.on("error", reject);
});
}
/**
* Get file extension from URL or content-type
*/
function getExtensionFromUrl(url, contentType) {
// Try to get extension from URL
const urlPath = new URL(url).pathname;
const urlExt = path.extname(urlPath).toLowerCase();
if (SUPPORTED_IMAGE_EXTENSIONS.includes(urlExt)) {
return urlExt;
}
// Fall back to content-type
if (contentType) {
const mimeToExt = {
'image/svg+xml': '.svg',
'image/png': '.png',
'image/jpeg': '.jpg',
'image/jpg': '.jpg'
};
const type = contentType.split(';')[0].trim();
return mimeToExt[type] || '.png';
}
return '.png'; // Default fallback
}
/**
* Parse command line flags
*/
function parseFlags(args) {
const flags = {};
for (let i = 0; i < args.length; i++) {
if (args[i].startsWith('--')) {
const key = args[i].substring(2);
const nextArg = args[i + 1];
// Check if next argument exists and is not another flag
if (nextArg !== undefined && !nextArg.startsWith("--")) {
flags[key] = nextArg;
i++; // Skip next argument since it's the value
} else {
// Flag without a value or next item is another flag
flags[key] = undefined;
}
}
}
return flags;
}
/**
* Validate metadata fields using Zod
*/
function validateMetadata(metadata) {
const result = MetadataSchema.safeParse(metadata);
if (!result.success) {
return result.error.issues.map(err => {
const field = err.path.join('.');
return `${field}: ${err.message}`;
});
}
return [];
}
/**
* Set (add or update) an asset
*/
async function setAsset(caipId, options) {
const paths = getAssetPaths(caipId);
const parsed = parseCAIP19(caipId);
const labels = parseLabels(options.labels);
// Check if asset already exists
let existingMetadata = null;
let isNewAsset = false;
try {
const metadataContent = await readFile(paths.metadataFile, 'utf8');
existingMetadata = JSON.parse(metadataContent);
console.log(`Updating existing asset: ${caipId}`);
} catch (err) {
if (err.code === 'ENOENT') {
console.log(`Creating new asset: ${caipId}`);
isNewAsset = true;
} else {
throw err;
}
}
// For new assets, ensure required fields are provided
if (isNewAsset) {
const missingFields = [];
if (!options.name) missingFields.push('--name');
if (!options.symbol) missingFields.push('--symbol');
if (options.decimals === undefined) missingFields.push('--decimals');
if (!options.image) missingFields.push('--image');
if (missingFields.length > 0) {
throw new Error(`Missing required fields for new asset: ${missingFields.join(', ')}`);
}
}
// Create directories if they don't exist
await mkdir(paths.metadataDir, { recursive: true });
await mkdir(paths.iconDir, { recursive: true });
await mkdir(paths.labelsDir, { recursive: true });
// Build or update metadata
const metadata = existingMetadata || {};
// Handle image update/creation
if (options.image) {
let imageSource = options.image;
let imageExt;
let tempDownloadPath = null;
try {
// Check if image is a URL
if (isUrl(options.image)) {
console.log(`Downloading image from URL: ${options.image}`);
// Download to temporary location first
tempDownloadPath = path.join(
paths.iconDir,
`temp-download-${Date.now()}`,
);
const contentType = await downloadFile(options.image, tempDownloadPath);
imageExt = getExtensionFromUrl(options.image, contentType);
imageSource = tempDownloadPath;
console.log(`✓ Downloaded image (${contentType})`);
} else {
// Local file path
imageExt = path.extname(options.image).toLowerCase();
if (!SUPPORTED_IMAGE_EXTENSIONS.includes(imageExt)) {
throw new Error(
`Unsupported image format: ${imageExt}. Supported: ${SUPPORTED_IMAGE_EXTENSIONS.join(", ")}`,
);
}
}
// Capture old icon path before saving new one (to avoid finding the new file)
const oldIcon = isNewAsset ? null : await findExistingIcon(paths.iconFileBase);
// Copy/move image to final location with correct name
const iconFile = `${paths.iconFileBase}${imageExt}`;
await copyFile(imageSource, iconFile);
console.log(
`✓ ${isNewAsset ? "Saved" : "Updated"} image to: ${iconFile}`,
);
// Remove old icon if updating and extension changed
if (oldIcon && oldIcon !== iconFile) {
fs.unlinkSync(oldIcon);
console.log(`✓ Removed old icon: ${oldIcon}`);
}
// Update metadata logo path
metadata.logo = `./icons/${parsed.chainNamespace}/${parsed.assetId}${imageExt}`;
} finally {
// Clean up temp file if we downloaded (always runs, even on error)
if (tempDownloadPath) {
try {
fs.unlinkSync(tempDownloadPath);
} catch (err) {
// Ignore cleanup errors
}
}
}
}
// Update fields (only if provided, or if new asset and required)
if (options.name) {
metadata.name = options.name;
}
if (options.symbol) {
metadata.symbol = options.symbol;
}
if (options.decimals !== undefined) {
metadata.decimals = parseInt(options.decimals, 10);
}
// Handle optional fields
if (options.erc20 !== undefined) {
metadata.erc20 = options.erc20 === 'true';
} else if (isNewAsset && parsed.assetId.startsWith('erc20:')) {
metadata.erc20 = true;
}
if (options.spl !== undefined) {
metadata.spl = options.spl === 'true';
} else if (isNewAsset && parsed.assetId.startsWith('spl:')) {
metadata.spl = true;
}
// Validate metadata
const errors = validateMetadata(metadata);
if (errors.length > 0) {
throw new Error(`Metadata validation failed:\n${errors.join('\n')}`);
}
// Write metadata file
await writeFile(paths.metadataFile, JSON.stringify(metadata, null, 2) + '\n');
console.log(`✓ ${isNewAsset ? 'Created' : 'Updated'} metadata file: ${paths.metadataFile}`);
if (labels !== undefined) {
const labelPayload = { labels };
await writeFile(
paths.labelsFile,
JSON.stringify(labelPayload, null, 2) + "\n",
);
console.log(
`✓ ${isNewAsset ? "Created" : "Updated"} labels file: ${paths.labelsFile}`,
);
}
console.log(`\n✓ Asset ${isNewAsset ? 'added' : 'updated'} successfully!`);
console.log('\nNext steps:');
console.log('1. Review the changes');
console.log('2. Rebuild the contract-map.json: node buildindex.js');
console.log('3. Commit and push your changes');
}
/**
* Verify an asset's files exist and are valid
*/
async function verifyAsset(caipId) {
console.log(`Verifying asset: ${caipId}`);
const paths = getAssetPaths(caipId);
const issues = [];
// Check metadata file
let metadata;
try {
const metadataContent = await readFile(paths.metadataFile, "utf8");
metadata = JSON.parse(metadataContent);
console.log("✓ Metadata file exists and is valid JSON");
} catch (err) {
issues.push(`Metadata file error: ${err.message}`);
}
if (metadata) {
// Validate metadata structure
const errors = validateMetadata(metadata);
if (errors.length > 0) {
issues.push(...errors.map((e) => `Metadata validation: ${e}`));
} else {
console.log("✓ Metadata structure is valid");
}
// Check if icon file exists
const iconFile = await findExistingIcon(paths.iconFileBase);
if (iconFile) {
console.log(`✓ Icon file exists: ${iconFile}`);
// Check if logo path in metadata matches actual file
const expectedLogoPath = path.basename(iconFile);
if (!metadata.logo) {
issues.push('Logo path mismatch: metadata is missing the logo field');
} else {
const metadataLogoPath = path.basename(metadata.logo);
if (expectedLogoPath !== metadataLogoPath) {
issues.push(
`Logo path mismatch: metadata references "${metadataLogoPath}" but file is "${expectedLogoPath}"`,
);
}
}
} else {
issues.push("Icon file not found");
}
}
// Check labels file when present
try {
const labelsContent = await readFile(paths.labelsFile, "utf8");
const labelsJson = JSON.parse(labelsContent);
const labelsValidation = LabelFileSchema.safeParse(labelsJson);
if (!labelsValidation.success) {
const errors = labelsValidation.error.issues.map((err) => {
const field = err.path.join(".");
return `${field}: ${err.message}`;
});
issues.push(...errors.map((e) => `Labels validation: ${e}`));
} else {
console.log("✓ Labels file exists and is valid");
}
} catch (err) {
if (err.code !== "ENOENT") {
issues.push(`Labels file error: ${err.message}`);
}
}
if (issues.length > 0) {
console.log("\n⚠ Issues found:");
issues.forEach((issue) => console.log(` - ${issue}`));
process.exit(1);
} else {
console.log("\n✓ Asset verification passed!");
}
}
/**
* List assets in a namespace
*/
async function listAssets(namespace) {
console.log(`Listing assets in namespace: ${namespace}`);
const metadataDir = path.join(__dirname, 'metadata', namespace);
try {
const files = await readdir(metadataDir);
const jsonFiles = files.filter(f => f.endsWith('.json'));
console.log(`\nFound ${jsonFiles.length} assets:\n`);
for (const file of jsonFiles.sort()) {
const assetId = file.replace('.json', '');
const caipId = `${namespace}/${assetId}`;
const metadataPath = path.join(metadataDir, file);
try {
const content = await readFile(metadataPath, 'utf8');
const metadata = JSON.parse(content);
console.log(` ${caipId}`);
console.log(` Name: ${metadata.name}`);
console.log(` Symbol: ${metadata.symbol}`);
console.log(` Decimals: ${metadata.decimals}`);
} catch (err) {
console.log(` ${caipId} (error reading metadata: ${err.message})`);
}
}
} catch (err) {
if (err.code === 'ENOENT') {
console.log('No assets found in this namespace.');
} else {
throw err;
}
}
}
/**
* Display help information
*/
function showHelp() {
console.log(`
CAIP-19 Asset Update CLI Tool
Usage:
node cli-update-asset.js <command> [options]
Commands:
set Add a new asset or update an existing one
verify Verify an asset's files exist and are valid
list List all assets in a namespace
help Show this help message
Set Command Options:
--caip <id> CAIP-19 asset identifier (required)
Format: namespace:chainId/assetNamespace:assetReference
Example: eip155:1/erc20:0x6B175474E89094C44Da98b954EedeAC495271d0F
--name <name> Asset name (required for new assets)
--symbol <symbol> Asset symbol (required for new assets)
--decimals <num> Number of decimals (required for new assets)
--image <path> Path to image file or URL (required for new assets)
Supports: .svg, .png, .jpg, .jpeg
Can be a local file path or HTTP/HTTPS URL
--labels <value> Labels for the asset (optional)
Comma-separated: "stable_coin,blue_chip"
Or JSON array: '["stable_coin","blue_chip"]'
--erc20 <bool> Whether this is an ERC20 token (true|false - optional, default: auto-detect)
--spl <bool> Whether this is a Solana SPL token (true|false - optional, default: auto-detect)
Verify Command Options:
--caip <id> CAIP-19 asset identifier (required)
List Command Options:
--namespace <ns> Chain namespace (required)
Example: eip155:1, eip155:137, etc.
Examples:
# Add a new token with a local image file
node cli-update-asset.js set \\
--caip "eip155:1/erc20:0x1234567890123456789012345678901234567890" \\
--name "My Token" \\
--symbol "MTK" \\
--decimals 18 \\
--image ./my-token-logo.svg
# Add a new token with an image URL
node cli-update-asset.js set \\
--caip "eip155:1/erc20:0x1234567890123456789012345678901234567890" \\
--name "My Token" \\
--symbol "MTK" \\
--decimals 18 \\
--image "https://example.com/logo.svg"
# Update token name and image
node cli-update-asset.js set \\
--caip "eip155:1/erc20:0x1234567890123456789012345678901234567890" \\
--name "My New Token Name" \\
--image ./new-logo.png
# Update labels
node cli-update-asset.js set \\
--caip "eip155:1/erc20:0x6B175474E89094C44Da98b954EedeAC495271d0F" \\
--labels "stable_coin,blue_chip"
# Update just the image
node cli-update-asset.js set \\
--caip "eip155:1/erc20:0x6B175474E89094C44Da98b954EedeAC495271d0F" \\
--image ./new-dai-logo.svg
# Verify an asset
node cli-update-asset.js verify \\
--caip "eip155:1/erc20:0x6B175474E89094C44Da98b954EedeAC495271d0F"
# List all assets on Ethereum mainnet
node cli-update-asset.js list --namespace "eip155:1"
Notes:
- Supported image formats: .svg, .png, .jpg, .jpeg
- After adding/updating assets, rebuild the index: node buildindex.js
- Follow CAIP-19 standard for asset identifiers
- Icon files should be square and high resolution (preferably vector/svg)
- The 'set' command automatically detects whether to add or update
`);
}
/**
* Main CLI handler
*/
async function main() {
try {
const flags = parseFlags(args.slice(1));
switch (command) {
case 'set':
case 'add':
case 'update':
{
const validationResult = SetCommandFlagsSchema.safeParse(flags);
if (!validationResult.success) {
const errors = validationResult.error.issues.map(err =>
`${err.path.join('.')}: ${err.message}`
).join('\n');
throw new Error(`Invalid flags:\n${errors}`);
}
if (!flags.caip) {
throw new Error('--caip flag is required');
}
await setAsset(flags.caip, flags);
}
break;
case 'verify':
{
const validationResult = VerifyCommandFlagsSchema.safeParse(flags);
if (!validationResult.success) {
const errors = validationResult.error.issues.map(err =>
`${err.path.join('.')}: ${err.message}`
).join('\n');
throw new Error(`Invalid flags:\n${errors}`);
}
if (!flags.caip) {
throw new Error('--caip flag is required');
}
await verifyAsset(flags.caip);
}
break;
case 'list':
{
const validationResult = ListCommandFlagsSchema.safeParse(flags);
if (!validationResult.success) {
const errors = validationResult.error.issues.map(err =>
`${err.path.join('.')}: ${err.message}`
).join('\n');
throw new Error(`Invalid flags:\n${errors}`);
}
if (!flags.namespace) {
throw new Error('--namespace flag is required');
}
await listAssets(flags.namespace);
}
break;
case 'help':
case '--help':
case '-h':
showHelp();
break;
default:
console.error(`Unknown command: ${command}\n`);
showHelp();
process.exit(1);
}
} catch (err) {
console.error(`\n❌ Error: ${err.message}\n`);
if (err.stack && process.env.DEBUG) {
console.error(err.stack);
}
process.exit(1);
}
}
// Run if executed directly
if (require.main === module) {
main();
}
module.exports = {
parseCAIP19,
parseLabels,
getAssetPaths,
validateMetadata,
setAsset,
verifyAsset,
listAssets,
};