minara 0.4.6 → 0.5.1

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.
@@ -2,7 +2,7 @@ import { Command } from 'commander';
2
2
  import { input } from '@inquirer/prompts';
3
3
  import { transfer } from '../api/crosschain.js';
4
4
  import { requireAuth } from '../config.js';
5
- import { success, spinner, assertApiOk, selectChain, wrapAction, requireTransactionConfirmation, lookupToken, validateAddress } from '../utils.js';
5
+ import { success, spinner, assertApiOk, selectChain, wrapAction, requireTransactionConfirmation, lookupToken, validateAddress, parseChainOption, assertTokenOnChain } from '../utils.js';
6
6
  import { requireTouchId } from '../touchid.js';
7
7
  import { printTxResult } from '../formatters.js';
8
8
  export const transferCommand = new Command('transfer')
@@ -15,14 +15,32 @@ export const transferCommand = new Command('transfer')
15
15
  .option('-y, --yes', 'Skip confirmation')
16
16
  .action(wrapAction(async (opts) => {
17
17
  const creds = requireAuth();
18
+ // ── 0. Validate CLI options early ────────────────────────────────────
19
+ if (opts.amount) {
20
+ const amountNum = parseFloat(opts.amount);
21
+ if (isNaN(amountNum) || amountNum <= 0) {
22
+ throw new Error('Amount must be a positive number');
23
+ }
24
+ }
25
+ const chainOpt = opts.chain ? parseChainOption(opts.chain) : undefined;
26
+ if (opts.to) {
27
+ if (!chainOpt) {
28
+ throw new Error('--chain is required when --to is provided');
29
+ }
30
+ const addrValidation = validateAddress(opts.to, chainOpt);
31
+ if (addrValidation !== true) {
32
+ throw new Error(addrValidation);
33
+ }
34
+ }
18
35
  // ── 1. Chain ─────────────────────────────────────────────────────────
19
- const chain = opts.chain ?? await selectChain();
36
+ const chain = chainOpt ?? await selectChain();
20
37
  // ── 2. Token ─────────────────────────────────────────────────────────
21
38
  const tokenInput = opts.token ?? await input({
22
39
  message: 'Token (address or ticker, native = 0x0…0):',
23
40
  validate: (v) => (v.length > 0 ? true : 'Token is required'),
24
41
  });
25
42
  const tokenInfo = await lookupToken(tokenInput);
43
+ assertTokenOnChain(tokenInfo, chain);
26
44
  // ── 3. Amount ────────────────────────────────────────────────────────
27
45
  const amount = opts.amount ?? await input({
28
46
  message: 'Amount to send:',
@@ -32,10 +50,10 @@ export const transferCommand = new Command('transfer')
32
50
  },
33
51
  });
34
52
  // ── 4. Recipient ─────────────────────────────────────────────────────
35
- const recipient = opts.to ?? await input({
53
+ const recipient = (opts.to ?? await input({
36
54
  message: 'Recipient address:',
37
55
  validate: (v) => validateAddress(v, chain),
38
- });
56
+ })).trim();
39
57
  // ── 5. Confirm & Touch ID ──────────────────────────────────────────
40
58
  if (!opts.yes) {
41
59
  await requireTransactionConfirmation(`Transfer ${amount} → ${recipient} · ${chain}`, tokenInfo, { chain, amount, destination: recipient });
@@ -3,7 +3,7 @@ import { input } from '@inquirer/prompts';
3
3
  import chalk from 'chalk';
4
4
  import { transfer, getAssets } from '../api/crosschain.js';
5
5
  import { requireAuth } from '../config.js';
6
- import { success, spinner, assertApiOk, selectChain, wrapAction, requireTransactionConfirmation, lookupToken, validateAddress } from '../utils.js';
6
+ import { success, spinner, assertApiOk, selectChain, wrapAction, requireTransactionConfirmation, lookupToken, validateAddress, parseChainOption, assertTokenOnChain, sanitizeTerminal } from '../utils.js';
7
7
  import { requireTouchId } from '../touchid.js';
8
8
  import { printTxResult } from '../formatters.js';
9
9
  export const withdrawCommand = new Command('withdraw')
@@ -15,37 +15,57 @@ export const withdrawCommand = new Command('withdraw')
15
15
  .option('-y, --yes', 'Skip confirmation')
16
16
  .action(wrapAction(async (opts) => {
17
17
  const creds = requireAuth();
18
- // ── 1. Show current assets for reference ─────────────────────────────
19
- const assetsSpin = spinner('Fetching your assets…');
20
- const assetsRes = await getAssets(creds.accessToken);
21
- assetsSpin.stop();
22
- if (assetsRes.success && assetsRes.data) {
23
- const assets = assetsRes.data;
24
- if (Array.isArray(assets) && assets.length > 0) {
25
- console.log('');
26
- console.log(chalk.dim('Your current assets:'));
27
- for (const asset of assets.slice(0, 15)) {
28
- const sym = asset.symbol ?? asset.tokenSymbol ?? '';
29
- const bal = asset.balance ?? asset.amount ?? '';
30
- const ch = asset.chain ?? asset.chainName ?? '';
31
- if (sym || bal) {
32
- console.log(chalk.dim(` ${sym} ${bal} (${ch})`));
18
+ // ── 0. Validate CLI options early ────────────────────────────────────
19
+ if (opts.amount) {
20
+ const amountNum = parseFloat(opts.amount);
21
+ if (isNaN(amountNum) || amountNum <= 0) {
22
+ throw new Error('Amount must be a positive number');
23
+ }
24
+ }
25
+ const chainOpt = opts.chain ? parseChainOption(opts.chain) : undefined;
26
+ if (opts.to) {
27
+ if (!chainOpt) {
28
+ throw new Error('--chain is required when --to is provided');
29
+ }
30
+ const addrValidation = validateAddress(opts.to, chainOpt);
31
+ if (addrValidation !== true) {
32
+ throw new Error(addrValidation);
33
+ }
34
+ }
35
+ // ── 1. Show current assets for reference (only in interactive mode)
36
+ if (!opts.chain && !opts.token && !opts.amount && !opts.to) {
37
+ const assetsSpin = spinner('Fetching your assets…');
38
+ const assetsRes = await getAssets(creds.accessToken);
39
+ assetsSpin.stop();
40
+ if (assetsRes.success && assetsRes.data) {
41
+ const assets = assetsRes.data;
42
+ if (Array.isArray(assets) && assets.length > 0) {
43
+ console.log('');
44
+ console.log(chalk.dim('Your current assets:'));
45
+ for (const asset of assets.slice(0, 15)) {
46
+ const sym = sanitizeTerminal(asset.symbol ?? asset.tokenSymbol ?? '');
47
+ const bal = sanitizeTerminal(asset.balance ?? asset.amount ?? '');
48
+ const ch = sanitizeTerminal(asset.chain ?? asset.chainName ?? '');
49
+ if (sym || bal) {
50
+ console.log(chalk.dim(` ${sym} ${bal} (${ch})`));
51
+ }
33
52
  }
53
+ if (assets.length > 15) {
54
+ console.log(chalk.dim(` … and ${assets.length - 15} more`));
55
+ }
56
+ console.log('');
34
57
  }
35
- if (assets.length > 15) {
36
- console.log(chalk.dim(` … and ${assets.length - 15} more`));
37
- }
38
- console.log('');
39
58
  }
40
59
  }
41
60
  // ── 2. Chain ─────────────────────────────────────────────────────────
42
- const chain = opts.chain ?? await selectChain('Withdraw on which blockchain?');
61
+ const chain = chainOpt ?? await selectChain('Withdraw on which blockchain?');
43
62
  // ── 3. Token ─────────────────────────────────────────────────────────
44
63
  const tokenInput = opts.token ?? await input({
45
64
  message: `Token on ${chalk.cyan(chain)} (address or ticker, native = ${'0x' + '0'.repeat(40)}):`,
46
65
  validate: (v) => (v.length > 0 ? true : 'Token is required'),
47
66
  });
48
67
  const tokenInfo = await lookupToken(tokenInput);
68
+ assertTokenOnChain(tokenInfo, chain);
49
69
  // ── 4. Amount ────────────────────────────────────────────────────────
50
70
  const amount = opts.amount ?? await input({
51
71
  message: 'Amount to withdraw:',
@@ -55,10 +75,10 @@ export const withdrawCommand = new Command('withdraw')
55
75
  },
56
76
  });
57
77
  // ── 5. Destination ───────────────────────────────────────────────────
58
- const recipient = opts.to ?? await input({
78
+ const recipient = (opts.to ?? await input({
59
79
  message: 'Destination address (your external wallet):',
60
80
  validate: (v) => validateAddress(v, chain),
61
- });
81
+ })).trim();
62
82
  // ── 6. Confirm & Touch ID ──────────────────────────────────────────
63
83
  if (!opts.yes) {
64
84
  await requireTransactionConfirmation(`Withdraw ${amount} → ${recipient} · ${chain}`, tokenInfo, { chain, amount, destination: recipient });
package/dist/config.d.ts CHANGED
@@ -8,6 +8,7 @@ export interface AppConfig {
8
8
  touchId?: boolean;
9
9
  confirmBeforeTransaction?: boolean;
10
10
  }
11
+ export declare const DEFAULT_BASE_URL = "https://api.minara.ai";
11
12
  export declare function loadConfig(): AppConfig;
12
13
  export declare function saveConfig(config: Partial<AppConfig>): void;
13
14
  export declare function getMinaraDir(): string;
package/dist/config.js CHANGED
@@ -5,16 +5,34 @@ const MINARA_DIR = join(homedir(), '.minara');
5
5
  const CREDENTIALS_FILE = join(MINARA_DIR, 'credentials.json');
6
6
  const CONFIG_FILE = join(MINARA_DIR, 'config.json');
7
7
  // ─── Directory ───────────────────────────────────────────────────────────────
8
+ /** Best-effort chmod — ignored on platforms / filesystems that don't support it. */
9
+ function tightenMode(path, mode) {
10
+ try {
11
+ chmodSync(path, mode);
12
+ }
13
+ catch {
14
+ // e.g. Windows or a read-only mount — nothing more we can do
15
+ }
16
+ }
8
17
  function ensureDir() {
9
18
  if (!existsSync(MINARA_DIR)) {
10
19
  mkdirSync(MINARA_DIR, { recursive: true });
11
- chmodSync(MINARA_DIR, 0o700);
12
20
  }
21
+ // Re-apply on every call: a pre-existing directory may have looser permissions
22
+ tightenMode(MINARA_DIR, 0o700);
23
+ }
24
+ /**
25
+ * Write a private file. `mode` in writeFileSync only applies when the file is
26
+ * created, so permissions are re-applied explicitly for pre-existing files.
27
+ */
28
+ function writePrivateFile(path, content) {
29
+ writeFileSync(path, content, { encoding: 'utf-8', mode: 0o600 });
30
+ tightenMode(path, 0o600);
13
31
  }
14
32
  // ─── Credentials ─────────────────────────────────────────────────────────────
15
33
  export function saveCredentials(creds) {
16
34
  ensureDir();
17
- writeFileSync(CREDENTIALS_FILE, JSON.stringify(creds, null, 2), { encoding: 'utf-8', mode: 0o600 });
35
+ writePrivateFile(CREDENTIALS_FILE, JSON.stringify(creds, null, 2));
18
36
  }
19
37
  export function loadCredentials() {
20
38
  if (!existsSync(CREDENTIALS_FILE))
@@ -34,7 +52,7 @@ export function clearCredentials() {
34
52
  }
35
53
  catch {
36
54
  // Best-effort: if file deletion fails, overwrite with empty JSON
37
- writeFileSync(CREDENTIALS_FILE, '{}', 'utf-8');
55
+ writePrivateFile(CREDENTIALS_FILE, '{}');
38
56
  }
39
57
  }
40
58
  export function requireAuth() {
@@ -45,8 +63,9 @@ export function requireAuth() {
45
63
  }
46
64
  return creds;
47
65
  }
66
+ export const DEFAULT_BASE_URL = 'https://api.minara.ai';
48
67
  const DEFAULT_CONFIG = {
49
- baseUrl: 'https://api.minara.ai',
68
+ baseUrl: DEFAULT_BASE_URL,
50
69
  confirmBeforeTransaction: true,
51
70
  };
52
71
  export function loadConfig() {
@@ -64,7 +83,7 @@ export function saveConfig(config) {
64
83
  ensureDir();
65
84
  const current = loadConfig();
66
85
  const merged = { ...current, ...config };
67
- writeFileSync(CONFIG_FILE, JSON.stringify(merged, null, 2), { encoding: 'utf-8', mode: 0o600 });
86
+ writePrivateFile(CONFIG_FILE, JSON.stringify(merged, null, 2));
68
87
  }
69
88
  export function getMinaraDir() {
70
89
  ensureDir();
@@ -1,3 +1,8 @@
1
+ import type { CrossChainSwapsSimulateResultDto, CrossChainSwapsSimulateErrorDto } from './types.js';
2
+ /** Convert wei (10^18) string to USD decimal string */
3
+ export declare function formatWeiToUsd(weiStr: string): string;
4
+ /** Convert BigInt amount string using token decimals */
5
+ export declare function formatTokenAmount(amountStr: string, decimals: number): string;
1
6
  /** Enable raw JSON output (all formatters fall back to JSON.stringify). */
2
7
  export declare function setRawJson(enabled: boolean): void;
3
8
  /** Check if raw JSON output mode is active. */
@@ -57,3 +62,7 @@ export declare function printFearGreed(data: Record<string, unknown>): void;
57
62
  * Pretty-print BTC/crypto metrics — flatten currentQuote, skip ohlcvQuotes.
58
63
  */
59
64
  export declare function printCryptoMetrics(data: Record<string, unknown>): void;
65
+ /** Check if a simulation result is an error */
66
+ export declare function isSimulateError(item: CrossChainSwapsSimulateResultDto | CrossChainSwapsSimulateErrorDto): item is CrossChainSwapsSimulateErrorDto;
67
+ /** Pretty-print swap simulation result with wei-to-USD conversion */
68
+ export declare function printSwapSimulation(result: CrossChainSwapsSimulateResultDto | CrossChainSwapsSimulateErrorDto): void;
@@ -5,6 +5,36 @@
5
5
  // ═══════════════════════════════════════════════════════════════════════════
6
6
  import chalk from 'chalk';
7
7
  import Table from 'cli-table3';
8
+ import { sanitizeTerminal, sanitizeDeep } from './utils.js';
9
+ // ─── Wei / BigInt formatting ──────────────────────────────────────────────
10
+ /** Convert wei (10^18) string to USD decimal string */
11
+ export function formatWeiToUsd(weiStr) {
12
+ try {
13
+ const wei = BigInt(weiStr);
14
+ // Divide by 10^18 (wei to ether conversion)
15
+ const dollars = Number(wei) / 1e18;
16
+ return dollars.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 6 });
17
+ }
18
+ catch {
19
+ return weiStr; // fallback to original if parsing fails
20
+ }
21
+ }
22
+ /** Convert BigInt amount string using token decimals */
23
+ export function formatTokenAmount(amountStr, decimals) {
24
+ try {
25
+ const amount = BigInt(amountStr);
26
+ const value = Number(amount) / Math.pow(10, decimals);
27
+ return value.toLocaleString('en-US', { maximumFractionDigits: decimals });
28
+ }
29
+ catch {
30
+ return amountStr; // fallback to original if parsing fails
31
+ }
32
+ }
33
+ /** Check if a string looks like a wei value (large BigInt string) */
34
+ function isWeiString(value) {
35
+ // Wei strings are typically large numbers (18+ digits)
36
+ return /^\d{15,}$/.test(value);
37
+ }
8
38
  // ─── Raw JSON mode ───────────────────────────────────────────────────────
9
39
  let _rawJson = false;
10
40
  /** Enable raw JSON output (all formatters fall back to JSON.stringify). */
@@ -30,6 +60,9 @@ export function formatLabel(key) {
30
60
  }
31
61
  /** Smart-format a single value for terminal display. */
32
62
  export function formatValue(value, key) {
63
+ // API / on-chain strings are untrusted: strip terminal control sequences
64
+ if (typeof value === 'string')
65
+ value = sanitizeTerminal(value);
33
66
  if (value === null || value === undefined || value === '')
34
67
  return chalk.dim('—');
35
68
  if (typeof value === 'boolean')
@@ -58,6 +91,10 @@ export function formatValue(value, key) {
58
91
  // Hex addresses — must check before numeric coercion (0x… is valid Number)
59
92
  if (/^0x[0-9a-fA-F]{20,}$/.test(value))
60
93
  return chalk.yellow(value);
94
+ // Wei-format USD fee strings (key contains "FeeInUsd" and value is large BigInt string)
95
+ if (key && /FeeInUsd$/i.test(key) && isWeiString(value)) {
96
+ return `$${formatWeiToUsd(value)}`;
97
+ }
61
98
  // Numeric string that looks like a price / amount
62
99
  const num = Number(value);
63
100
  if (!isNaN(num) && value.trim() !== '') {
@@ -83,7 +120,7 @@ export function formatValue(value, key) {
83
120
  if (value.length === 0)
84
121
  return chalk.dim('—');
85
122
  if (value.every((v) => typeof v === 'string' || typeof v === 'number')) {
86
- return value.join(', ');
123
+ return sanitizeTerminal(value.join(', '));
87
124
  }
88
125
  return chalk.dim(`[${value.length} items]`);
89
126
  }
@@ -91,11 +128,11 @@ export function formatValue(value, key) {
91
128
  // Shallow nested — show as inline key=value
92
129
  const entries = Object.entries(value).filter(([, v]) => v !== null && v !== undefined);
93
130
  if (entries.length <= 3) {
94
- return entries.map(([k, v]) => `${k}=${typeof v === 'string' ? v : JSON.stringify(v)}`).join(' ');
131
+ return sanitizeTerminal(entries.map(([k, v]) => `${k}=${typeof v === 'string' ? v : JSON.stringify(v)}`).join(' '));
95
132
  }
96
- return chalk.dim(JSON.stringify(value));
133
+ return chalk.dim(sanitizeTerminal(JSON.stringify(value)));
97
134
  }
98
- return String(value);
135
+ return sanitizeTerminal(value);
99
136
  }
100
137
  // ─── printKV ─────────────────────────────────────────────────────────────
101
138
  /**
@@ -111,6 +148,7 @@ export function printKV(data, indent = 2) {
111
148
  console.log(JSON.stringify(data, null, 2));
112
149
  return;
113
150
  }
151
+ data = sanitizeDeep(data);
114
152
  const entries = Object.entries(data).filter(([k, v]) => v !== undefined && v !== null && v !== '' && !HIDDEN_KEYS.test(k));
115
153
  if (entries.length === 0) {
116
154
  console.log(chalk.dim(`${' '.repeat(indent)}No data.`));
@@ -171,6 +209,7 @@ export function printTable(data, columns) {
171
209
  console.log(JSON.stringify(data, null, 2));
172
210
  return;
173
211
  }
212
+ data = sanitizeDeep(data);
174
213
  if (!data || (Array.isArray(data) && data.length === 0)) {
175
214
  console.log(chalk.dim(' No data.'));
176
215
  return;
@@ -221,7 +260,7 @@ export function printTxResult(data) {
221
260
  return;
222
261
  }
223
262
  if (typeof data !== 'object') {
224
- console.log(chalk.dim(` ${data}`));
263
+ console.log(chalk.dim(` ${sanitizeTerminal(data)}`));
225
264
  return;
226
265
  }
227
266
  const obj = data;
@@ -394,6 +433,7 @@ export function printFearGreed(data) {
394
433
  console.log(JSON.stringify(data, null, 2));
395
434
  return;
396
435
  }
436
+ data = sanitizeDeep(data);
397
437
  const entries = Object.entries(data).filter(([k, v]) => v !== undefined && v !== null && v !== '' && !HIDDEN_KEYS.test(k) && !FEAR_GREED_HIDDEN.has(k));
398
438
  if (entries.length === 0) {
399
439
  console.log(chalk.dim(' No data.'));
@@ -415,6 +455,7 @@ export function printCryptoMetrics(data) {
415
455
  console.log(JSON.stringify(data, null, 2));
416
456
  return;
417
457
  }
458
+ data = sanitizeDeep(data);
418
459
  const quote = data.currentQuote;
419
460
  const change24h = data.priceChange24h;
420
461
  // Build a flat display object from the quote
@@ -452,6 +493,87 @@ export function printCryptoMetrics(data) {
452
493
  console.log(` ${chalk.dim(label.padEnd(maxLen))} : ${val}`);
453
494
  }
454
495
  }
496
+ // ─── Swap Simulation ─────────────────────────────────────────────────────
497
+ /** Check if a simulation result is an error */
498
+ export function isSimulateError(item) {
499
+ return 'error' in item;
500
+ }
501
+ /** Pretty-print swap simulation result with wei-to-USD conversion */
502
+ export function printSwapSimulation(result) {
503
+ if (_rawJson) {
504
+ console.log(JSON.stringify(result, null, 2));
505
+ return;
506
+ }
507
+ // Token symbol / name come from third-party metadata
508
+ result = sanitizeDeep(result);
509
+ // Handle error case
510
+ if (isSimulateError(result)) {
511
+ console.log(chalk.red.bold(` Error: ${result.error}`));
512
+ if (result.message) {
513
+ console.log(chalk.dim(` Message: ${result.message}`));
514
+ }
515
+ return;
516
+ }
517
+ // Convert wei fees to USD (fees are always in 10^18 format)
518
+ const totalFeeUsd = formatWeiToUsd(result.totalFeeInUsd);
519
+ const gasFeeUsd = formatWeiToUsd(result.gasFeeInUsd);
520
+ const serviceFeeUsd = formatWeiToUsd(result.serviceFeeInUsd);
521
+ const lpFeeUsd = formatWeiToUsd(result.lpFeeInUsd);
522
+ // Sanity check: warn if total fee exceeds $1000
523
+ const totalFeeNum = parseFloat(totalFeeUsd.replace(/,/g, ''));
524
+ const feeWarning = totalFeeNum > 1000 ? chalk.yellow(' ⚠️ (unusually high)') : '';
525
+ // Print header
526
+ console.log('');
527
+ console.log(chalk.bold(' Simulation Result:'));
528
+ // Print token changes (using token.decimals for amount conversion)
529
+ if (result.increased.length > 0) {
530
+ console.log(chalk.green.bold(' Tokens Received:'));
531
+ for (const change of result.increased) {
532
+ const token = change.token;
533
+ const decimals = token.decimals ?? 18;
534
+ const amountFormatted = formatTokenAmount(change.amount, decimals);
535
+ const amountUsd = change.amountInUSD ? formatWeiToUsd(change.amountInUSD) : null;
536
+ console.log(` ${chalk.bold(`$${token.symbol}`)} — ${token.name}`);
537
+ console.log(` ${chalk.dim('Address')} : ${chalk.yellow(token.address)}`);
538
+ console.log(` ${chalk.dim('Amount')} : ${amountFormatted}`);
539
+ if (amountUsd)
540
+ console.log(` ${chalk.dim('Value')} : $${amountUsd}`);
541
+ }
542
+ }
543
+ if (result.decreased.length > 0) {
544
+ console.log(chalk.red.bold(' Tokens Spent:'));
545
+ for (const change of result.decreased) {
546
+ const token = change.token;
547
+ const decimals = token.decimals ?? 18;
548
+ const amountFormatted = formatTokenAmount(change.amount, decimals);
549
+ const amountUsd = change.amountInUSD ? formatWeiToUsd(change.amountInUSD) : null;
550
+ console.log(` ${chalk.bold(`$${token.symbol}`)} — ${token.name}`);
551
+ console.log(` ${chalk.dim('Address')} : ${chalk.yellow(token.address)}`);
552
+ console.log(` ${chalk.dim('Amount')} : ${amountFormatted}`);
553
+ if (amountUsd)
554
+ console.log(` ${chalk.dim('Value')} : $${amountUsd}`);
555
+ }
556
+ }
557
+ // Print fees
558
+ console.log('');
559
+ console.log(chalk.bold(' Fees:'));
560
+ console.log(` ${chalk.dim('Total Fee')} : $${totalFeeUsd}${feeWarning}`);
561
+ console.log(` ${chalk.dim('Gas Fee')} : $${gasFeeUsd}`);
562
+ console.log(` ${chalk.dim('Service Fee')} : $${serviceFeeUsd}`);
563
+ console.log(` ${chalk.dim('LP Fee')} : $${lpFeeUsd}`);
564
+ // Print other info
565
+ console.log('');
566
+ console.log(` ${chalk.dim('Slippage')} : ${result.slippageBps} bps`);
567
+ if (result.priceImpact !== null && result.priceImpact !== undefined) {
568
+ // -1 means price impact could not be calculated or is negligible
569
+ const impactStr = String(result.priceImpact).trim();
570
+ const impactNum = parseFloat(impactStr);
571
+ const impactDisplay = impactNum === -1 || impactStr === '-1'
572
+ ? chalk.dim('— (negligible)')
573
+ : `${impactStr}%`;
574
+ console.log(` ${chalk.dim('Price Impact')} : ${impactDisplay}`);
575
+ }
576
+ }
455
577
  // ─── Helpers ─────────────────────────────────────────────────────────────
456
578
  function truncate(str, len) {
457
579
  return str.length > len ? str.slice(0, len - 1) + '…' : str;
package/dist/touchid.d.ts CHANGED
@@ -13,6 +13,7 @@ export declare function verifyTouchId(reason?: string): void;
13
13
  * verification. Exits the process on failure.
14
14
  *
15
15
  * Call this before any sensitive financial operation.
16
- * On non-macOS platforms a warning is shown and execution continues.
16
+ * Fails closed: if Touch ID is enabled but cannot run on this platform, the
17
+ * operation is cancelled rather than silently skipping the check.
17
18
  */
18
19
  export declare function requireTouchId(): Promise<void>;
package/dist/touchid.js CHANGED
@@ -143,15 +143,17 @@ export function verifyTouchId(reason) {
143
143
  * verification. Exits the process on failure.
144
144
  *
145
145
  * Call this before any sensitive financial operation.
146
- * On non-macOS platforms a warning is shown and execution continues.
146
+ * Fails closed: if Touch ID is enabled but cannot run on this platform, the
147
+ * operation is cancelled rather than silently skipping the check.
147
148
  */
148
149
  export async function requireTouchId() {
149
150
  const config = loadConfig();
150
151
  if (!config.touchId)
151
152
  return; // Touch ID not enabled — no-op
152
153
  if (platform() !== 'darwin') {
153
- console.log(chalk.yellow('⚠'), 'Touch ID is only available on macOS. Skipping biometric check.');
154
- return;
154
+ console.error(chalk.red('✖'), 'Touch ID is enabled in your config but is only available on macOS. Operation cancelled.');
155
+ console.error(chalk.dim(' Run `minara config` to disable Touch ID protection on this machine.'));
156
+ process.exit(1);
155
157
  }
156
158
  console.log('');
157
159
  console.log(chalk.blue('🔐'), chalk.bold('Touch ID verification required'));
package/dist/types.d.ts CHANGED
@@ -123,6 +123,54 @@ export interface TransactionResult {
123
123
  status?: string;
124
124
  [key: string]: unknown;
125
125
  }
126
+ export interface TokenInfoDto {
127
+ name: string;
128
+ symbol: string;
129
+ address: string;
130
+ chainId: number;
131
+ decimals: number;
132
+ realDecimals: number;
133
+ price: number;
134
+ image?: string;
135
+ assetId?: string;
136
+ type?: string;
137
+ rank?: number | null;
138
+ slotIndex?: number | null;
139
+ }
140
+ export interface TokenChangeDto {
141
+ token: TokenInfoDto;
142
+ /** Amount of token changed (BigInt string, use token.decimals for conversion) */
143
+ amount: string;
144
+ /** Amount in USD (BigInt string in wei/10^18, may be null) */
145
+ amountInUSD: string | null;
146
+ }
147
+ export interface CrossChainSwapsSimulateResultDto {
148
+ /** Tokens that increased in balance */
149
+ increased: TokenChangeDto[];
150
+ /** Tokens that decreased in balance */
151
+ decreased: TokenChangeDto[];
152
+ /** Total fee in USD (BigInt string in wei/10^18) */
153
+ totalFeeInUsd: string;
154
+ /** Gas fee in USD (BigInt string in wei/10^18) */
155
+ gasFeeInUsd: string;
156
+ /** Service fee in USD (BigInt string in wei/10^18) */
157
+ serviceFeeInUsd: string;
158
+ /** LP fee in USD (BigInt string in wei/10^18) */
159
+ lpFeeInUsd: string;
160
+ /** Slippage in basis points */
161
+ slippageBps: number;
162
+ /** Price impact (may be null) */
163
+ priceImpact: string | null;
164
+ }
165
+ export interface CrossChainSwapsSimulateErrorDto {
166
+ error: string;
167
+ message?: string;
168
+ }
169
+ export type CrossChainSwapsSimulateItem = CrossChainSwapsSimulateResultDto | CrossChainSwapsSimulateErrorDto;
170
+ export interface CrossChainSwapsSimulateResponseDto {
171
+ success: boolean;
172
+ data: CrossChainSwapsSimulateItem[];
173
+ }
126
174
  export type SwapSide = 'buy' | 'sell';
127
175
  export interface CrossChainSwapDto {
128
176
  chain: Chain;
@@ -43,7 +43,8 @@ export async function checkForUpdate(currentVersion) {
43
43
  try {
44
44
  // Use cache to avoid hitting npm on every invocation
45
45
  const cached = readCache();
46
- if (cached && Date.now() - cached.checkedAt < CHECK_INTERVAL_MS) {
46
+ if (cached && typeof cached.latest === 'string' && /^\d+\.\d+\.\d+/.test(cached.latest)
47
+ && Date.now() - cached.checkedAt < CHECK_INTERVAL_MS) {
47
48
  return isNewer(cached.latest, currentVersion)
48
49
  ? formatNotice(currentVersion, cached.latest)
49
50
  : null;
@@ -58,7 +59,8 @@ export async function checkForUpdate(currentVersion) {
58
59
  if (!res.ok)
59
60
  return null;
60
61
  const { version: latest } = (await res.json());
61
- if (!latest)
62
+ // Only accept a plain semver string (it is printed to the terminal)
63
+ if (typeof latest !== 'string' || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(latest))
62
64
  return null;
63
65
  writeCache({ latest, checkedAt: Date.now() });
64
66
  return isNewer(latest, currentVersion)