minara 0.4.7 → 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.
@@ -3,7 +3,7 @@ import { input, select, confirm, number as numberPrompt } from '@inquirer/prompt
3
3
  import chalk from 'chalk';
4
4
  import * as perpsApi from '../api/perps.js';
5
5
  import { requireAuth } from '../config.js';
6
- import { success, info, warn, spinner, assertApiOk, formatOrderSide, wrapAction, requireTransactionConfirmation, validateAddress } from '../utils.js';
6
+ import { success, info, warn, spinner, assertApiOk, formatOrderSide, wrapAction, requireTransactionConfirmation, validateAddress, sanitizeTerminal } from '../utils.js';
7
7
  import { requireTouchId } from '../touchid.js';
8
8
  import { printTxResult, printTable, printKV, POSITION_COLUMNS, FILL_COLUMNS } from '../formatters.js';
9
9
  // ─── shared helpers ──────────────────────────────────────────────────────
@@ -21,6 +21,12 @@ function getSubAccountLabel(w) {
21
21
  const def = w.isDefault ? chalk.dim(' (default)') : '';
22
22
  return `${name}${def}`;
23
23
  }
24
+ /** Plain-text wallet label (no colors) for transaction confirmation rows. */
25
+ function walletText(w) {
26
+ return `${w.name ?? 'Unnamed'}${w.isDefault ? ' (default)' : ''}`;
27
+ }
28
+ /** Help text for `-y` on commands whose transaction confirmation cannot be skipped. */
29
+ const YES_COMPAT_OPT = ['-y, --yes', 'Accepted for compatibility; transaction confirmation still applies'];
24
30
  /**
25
31
  * Normalize the Hyperliquid sub-account summary into a consistent shape.
26
32
  * The API returns: { marginSummary: { accountValue, totalNtlPos, totalMarginUsed },
@@ -290,7 +296,7 @@ const depositCmd = new Command('deposit')
290
296
  .description('Deposit USDC into Hyperliquid perps (min 5 USDC)')
291
297
  .option('-a, --amount <amount>', 'USDC amount')
292
298
  .option(WALLET_OPT[0], WALLET_OPT[1])
293
- .option('-y, --yes', 'Skip confirmation')
299
+ .option(YES_COMPAT_OPT[0], YES_COMPAT_OPT[1])
294
300
  .action(wrapAction(async (opts) => {
295
301
  const creds = requireAuth();
296
302
  const resolved = await resolveWallet(creds.accessToken, opts.wallet, 'Deposit to which wallet?');
@@ -304,13 +310,11 @@ const depositCmd = new Command('deposit')
304
310
  console.error(chalk.red('✖'), 'Minimum deposit is 5 USDC');
305
311
  process.exit(1);
306
312
  }
307
- console.log(`\n Deposit : ${chalk.bold(amount)} USDC → ${getSubAccountLabel(wallet)}\n`);
308
- if (!opts.yes) {
309
- const ok = await confirm({ message: 'Confirm deposit?', default: true });
310
- if (!ok)
311
- return;
312
- }
313
- await requireTransactionConfirmation(`Deposit ${amount} USDC → ${wallet.name ?? 'Perps'}`);
313
+ // Single confirmation (always shown unless disabled in config)
314
+ await requireTransactionConfirmation(`Deposit ${amount} USDC → ${wallet.name ?? 'Perps'}`, undefined, {
315
+ amount: `${amount} USDC`,
316
+ extra: [['Wallet', walletText(wallet)]],
317
+ });
314
318
  await requireTouchId();
315
319
  const spin = spinner('Depositing…');
316
320
  const res = await perpsApi.deposit(creds.accessToken, { usdcAmount: amount, subAccountId: walletId });
@@ -325,9 +329,15 @@ const withdrawCmd = new Command('withdraw')
325
329
  .option('-a, --amount <amount>', 'USDC amount')
326
330
  .option('--to <address>', 'Destination address')
327
331
  .option(WALLET_OPT[0], WALLET_OPT[1])
328
- .option('-y, --yes', 'Skip confirmation')
332
+ .option(YES_COMPAT_OPT[0], YES_COMPAT_OPT[1])
329
333
  .action(wrapAction(async (opts) => {
330
334
  const creds = requireAuth();
335
+ // Validate a flag-supplied address the same way as the interactive prompt
336
+ if (opts.to) {
337
+ const addrCheck = validateAddress(opts.to, 'arbitrum');
338
+ if (addrCheck !== true)
339
+ throw new Error(addrCheck);
340
+ }
331
341
  const resolved = await resolveWallet(creds.accessToken, opts.wallet, 'Withdraw from which wallet?');
332
342
  if (!resolved)
333
343
  return;
@@ -335,18 +345,21 @@ const withdrawCmd = new Command('withdraw')
335
345
  const amount = opts.amount
336
346
  ? parseFloat(opts.amount)
337
347
  : await numberPrompt({ message: 'USDC amount to withdraw:', min: 0.01, required: true });
338
- const toAddress = opts.to ?? await input({
348
+ if (!amount || !Number.isFinite(amount) || amount <= 0) {
349
+ throw new Error('Amount must be a positive number');
350
+ }
351
+ const toAddress = (opts.to ?? await input({
339
352
  message: 'Destination address:',
340
353
  validate: (v) => validateAddress(v, 'arbitrum'),
341
- });
342
- console.log(`\n Withdraw : ${chalk.bold(amount)} USDC from ${getSubAccountLabel(wallet)} → ${chalk.yellow(toAddress)}\n`);
354
+ })).trim();
343
355
  warn('Withdrawals may take time to process.');
344
- if (!opts.yes) {
345
- const ok = await confirm({ message: 'Confirm withdrawal?', default: false });
346
- if (!ok)
347
- return;
348
- }
349
- await requireTransactionConfirmation(`Withdraw ${amount} USDC → ${toAddress}`);
356
+ // Single confirmation (always shown unless disabled in config)
357
+ await requireTransactionConfirmation(`Withdraw ${amount} USDC → ${toAddress}`, undefined, {
358
+ chain: 'Arbitrum',
359
+ amount: `${amount} USDC`,
360
+ destination: toAddress,
361
+ extra: [['Wallet', walletText(wallet)]],
362
+ });
350
363
  await requireTouchId();
351
364
  const spin = spinner('Withdrawing…');
352
365
  const res = await perpsApi.withdraw(creds.accessToken, { usdcAmount: amount, toAddress, subAccountId: walletId });
@@ -469,6 +482,11 @@ const orderCmd = new Command('order')
469
482
  .option('--tpsl <type>', 'Trigger type for market orders: tp (take profit) or sl (stop loss)', 'tp')
470
483
  .action(wrapAction(async (opts) => {
471
484
  const creds = requireAuth();
485
+ for (const [flag, value] of [['--price', opts.price], ['--size', opts.size]]) {
486
+ if (value !== undefined && !(Number(value) > 0)) {
487
+ throw new Error(`${flag} must be a positive number`);
488
+ }
489
+ }
472
490
  const resolved = await resolveWallet(creds.accessToken, opts.wallet, 'Place order on which wallet?');
473
491
  if (!resolved)
474
492
  return;
@@ -962,8 +980,18 @@ const leverageCmd = new Command('leverage')
962
980
  .option(WALLET_OPT[0], WALLET_OPT[1])
963
981
  .option('-s, --symbol <TOKEN>', 'Target token symbol (e.g. ETH, SOL, BTC)')
964
982
  .option('-l, --leverage <VALUE>', 'Leverage multiplier (e.g. 2, 3, 5, 10)')
983
+ .option('-m, --margin <MODE>', 'Margin mode: cross or isolated (default: cross when --symbol and --leverage are given)')
984
+ .option('-y, --yes', 'Skip transaction confirmation (Touch ID still required if enabled)')
965
985
  .action(wrapAction(async (opts) => {
966
986
  const creds = requireAuth();
987
+ let marginFlag;
988
+ if (opts.margin !== undefined) {
989
+ const m = opts.margin.toLowerCase();
990
+ if (m !== 'cross' && m !== 'isolated') {
991
+ throw new Error(`Invalid margin mode: ${opts.margin}. Use "cross" or "isolated".`);
992
+ }
993
+ marginFlag = m === 'cross';
994
+ }
967
995
  const resolved = await resolveWallet(creds.accessToken, opts.wallet, 'Update leverage on which wallet?');
968
996
  if (!resolved)
969
997
  return;
@@ -1021,9 +1049,13 @@ const leverageCmd = new Command('leverage')
1021
1049
  });
1022
1050
  }
1023
1051
  // Determine margin mode (cross vs isolated)
1024
- // In non-interactive mode with both symbol and leverage, default to cross margin
1052
+ // Explicit --margin wins; in non-interactive mode with both symbol and
1053
+ // leverage, default to cross margin (shown in the confirmation below).
1025
1054
  let isCross;
1026
- if (opts.symbol && opts.leverage) {
1055
+ if (marginFlag !== undefined) {
1056
+ isCross = marginFlag;
1057
+ }
1058
+ else if (opts.symbol && opts.leverage) {
1027
1059
  isCross = true;
1028
1060
  }
1029
1061
  else {
@@ -1035,6 +1067,18 @@ const leverageCmd = new Command('leverage')
1035
1067
  ],
1036
1068
  });
1037
1069
  }
1070
+ // Changing leverage / margin mode alters liquidation risk on real positions
1071
+ if (!opts.yes) {
1072
+ await requireTransactionConfirmation(`Set ${symbol} leverage to ${leverage}x (${isCross ? 'cross' : 'isolated'})`, undefined, {
1073
+ extra: [
1074
+ ['Wallet', walletText(wallet)],
1075
+ ['Symbol', symbol],
1076
+ ['Leverage', `${leverage}x (max ${maxLev}x)`],
1077
+ ['Margin', isCross ? 'Cross' : 'Isolated'],
1078
+ ],
1079
+ });
1080
+ }
1081
+ await requireTouchId();
1038
1082
  const spin = spinner('Updating leverage…');
1039
1083
  const res = await perpsApi.updateLeverage(creds.accessToken, { symbol, isCross, leverage: leverage, subAccountId: walletId });
1040
1084
  spin.stop();
@@ -1292,6 +1336,15 @@ const autopilotCmd = new Command('autopilot')
1292
1336
  break;
1293
1337
  case 'on':
1294
1338
  if (state.strategyId) {
1339
+ // Enabling lets the AI open / close real positions on this wallet
1340
+ await requireTransactionConfirmation(`Turn ON autopilot "${strategyDisplayName(state)}" — AI will trade on this wallet`, undefined, {
1341
+ extra: [
1342
+ ['Wallet', walletText(wallet)],
1343
+ ['Strategy', `${strategyDisplayName(state)} (${state.strategyId})`],
1344
+ ['Symbols', state.symbols?.join(', ') || '—'],
1345
+ ],
1346
+ });
1347
+ await requireTouchId();
1295
1348
  const spin = spinner('Enabling autopilot…');
1296
1349
  const res = await perpsApi.enableStrategy(creds.accessToken, state.strategyId);
1297
1350
  spin.stop();
@@ -1320,6 +1373,15 @@ const autopilotCmd = new Command('autopilot')
1320
1373
  default: state.symbols?.join(',') ?? '',
1321
1374
  });
1322
1375
  const symbols = symbolsInput.split(',').map((s) => s.trim().toUpperCase()).filter(Boolean);
1376
+ await requireTransactionConfirmation(`Update autopilot symbols for "${strategyDisplayName(state)}"`, undefined, {
1377
+ extra: [
1378
+ ['Wallet', walletText(wallet)],
1379
+ ['Status', state.active ? 'ON (takes effect immediately)' : 'OFF'],
1380
+ ['Current', state.symbols?.join(', ') || '—'],
1381
+ ['New', symbols.join(', ') || '—'],
1382
+ ],
1383
+ });
1384
+ await requireTouchId();
1323
1385
  const spin = spinner('Updating symbols…');
1324
1386
  const res = await perpsApi.updateStrategy(creds.accessToken, {
1325
1387
  strategyId: state.strategyId,
@@ -1355,6 +1417,14 @@ const autopilotCmd = new Command('autopilot')
1355
1417
  warn('Invalid JSON. Config not updated.');
1356
1418
  break;
1357
1419
  }
1420
+ await requireTransactionConfirmation(`Update autopilot config for "${strategyDisplayName(state)}"`, undefined, {
1421
+ extra: [
1422
+ ['Wallet', walletText(wallet)],
1423
+ ['Status', state.active ? 'ON (takes effect immediately)' : 'OFF'],
1424
+ ['Config', JSON.stringify(newConfig)],
1425
+ ],
1426
+ });
1427
+ await requireTouchId();
1358
1428
  const spin = spinner('Updating config…');
1359
1429
  const res = await perpsApi.updateStrategy(creds.accessToken, {
1360
1430
  strategyId: state.strategyId,
@@ -1423,6 +1493,14 @@ async function createNewStrategy(token, supported, walletId, wallet) {
1423
1493
  catch {
1424
1494
  warn('Invalid JSON — using default config.');
1425
1495
  }
1496
+ await requireTransactionConfirmation(`Create autopilot strategy on ${walletText(wallet)}`, undefined, {
1497
+ extra: [
1498
+ ['Wallet', walletText(wallet)],
1499
+ ['Symbols', symbols.join(', ') || '—'],
1500
+ ['Config', strategyConfig ? JSON.stringify(strategyConfig) : 'default'],
1501
+ ],
1502
+ });
1503
+ await requireTouchId();
1426
1504
  const spin = spinner('Creating autopilot strategy…');
1427
1505
  const res = await perpsApi.createStrategy(token, {
1428
1506
  symbols,
@@ -1916,8 +1994,25 @@ const askCmd = new Command('ask')
1916
1994
  const { interval, hours } = styleConfig[style] ?? styleConfig['day-trading'];
1917
1995
  const endTime = Date.now();
1918
1996
  const startTime = endTime - hours * 60 * 60 * 1000;
1919
- const marginInput = await input({ message: 'Margin in USD:', default: '1000' });
1920
- const leverageInput = await input({ message: 'Leverage:', default: '10' });
1997
+ const symbolMeta = assets.find((a) => a.name.toUpperCase() === symbol.toUpperCase());
1998
+ const maxLevForSymbol = symbolMeta?.maxLeverage ?? 50;
1999
+ const marginInput = await input({
2000
+ message: 'Margin in USD:',
2001
+ default: '1000',
2002
+ validate: (v) => (Number(v) > 0 ? true : 'Enter a positive number'),
2003
+ });
2004
+ const leverageInput = await input({
2005
+ message: 'Leverage:',
2006
+ default: '10',
2007
+ validate: (v) => {
2008
+ const n = Number(v);
2009
+ if (!(n >= 1))
2010
+ return 'Leverage must be a number >= 1';
2011
+ if (n > maxLevForSymbol)
2012
+ return `Max leverage for ${symbol} is ${maxLevForSymbol}x`;
2013
+ return true;
2014
+ },
2015
+ });
1921
2016
  const spin = spinner(`Analyzing ${symbol}…`);
1922
2017
  const res = await perpsApi.priceAnalysis(creds.accessToken, {
1923
2018
  symbol,
@@ -1937,7 +2032,8 @@ const askCmd = new Command('ask')
1937
2032
  console.log(chalk.bold(`AI Analysis — ${symbol} (${style}):`));
1938
2033
  console.log('');
1939
2034
  if (typeof data === 'string') {
1940
- console.log(data);
2035
+ // AI output is untrusted: keep line breaks, drop terminal control sequences
2036
+ console.log(sanitizeTerminal(data, { multiline: true }));
1941
2037
  }
1942
2038
  else {
1943
2039
  printKV(data);
@@ -1948,10 +2044,24 @@ const askCmd = new Command('ask')
1948
2044
  const recommendation = extractRecommendation(data, symbol, Number(marginInput), Number(leverageInput));
1949
2045
  if (!recommendation)
1950
2046
  return;
1951
- const { side, entryPrice, size } = recommendation;
2047
+ // The AI only suggests direction / entry / size. The order itself is a
2048
+ // market order, so bound it by live market data and the user's own inputs.
2049
+ const marginUSD = Number(marginInput);
2050
+ const requestedLev = Number(leverageInput);
2051
+ const quick = buildQuickOrderPlan(recommendation, symbolMeta, marginUSD, requestedLev);
2052
+ if ('error' in quick) {
2053
+ warn(quick.error);
2054
+ info('Place the order manually instead: minara perps order');
2055
+ return;
2056
+ }
2057
+ const { side, entryPrice } = recommendation;
2058
+ const { markPx, size } = quick;
1952
2059
  const sideLabel = side === 'buy' ? chalk.green.bold('LONG') : chalk.red.bold('SHORT');
1953
2060
  console.log(chalk.bold('Quick Order:'));
1954
- console.log(` ${sideLabel} ${chalk.bold(symbol)} | Entry ~$${entryPrice.toLocaleString()} | Size ${size} | ${Number(leverageInput)}x`);
2061
+ console.log(` ${sideLabel} ${chalk.bold(symbol)} | Market ~$${markPx.toLocaleString()} (AI entry ~$${entryPrice.toLocaleString()}) | Size ${size} | Notional ~${fmt(size * markPx)}`);
2062
+ if (quick.capped) {
2063
+ warn(`AI-suggested size ${recommendation.size} exceeds margin × leverage (${fmt(marginUSD)} × ${requestedLev}x) — capped to ${size}.`);
2064
+ }
1955
2065
  console.log('');
1956
2066
  const doQuick = await confirm({ message: 'Place this order now?', default: false });
1957
2067
  if (!doQuick)
@@ -1970,17 +2080,34 @@ const askCmd = new Command('ask')
1970
2080
  info('Turn off autopilot first: minara perps autopilot');
1971
2081
  return;
1972
2082
  }
2083
+ // The order uses the wallet's current leverage setting, not the value typed above
2084
+ const walletLev = orderWallet.address
2085
+ ? (await perpsApi.getUserLeverage(orderWallet.address)).find((l) => l.coin.toUpperCase() === symbol.toUpperCase())
2086
+ : undefined;
2087
+ const walletLevLabel = walletLev ? `${walletLev.leverageValue}x (${walletLev.leverageType})` : 'unknown';
2088
+ if (!walletLev || walletLev.leverageValue !== requestedLev) {
2089
+ warn(`This order uses the wallet's current ${symbol} leverage (${walletLevLabel}), not the ${requestedLev}x used for the analysis.`);
2090
+ info(`Change it first with: minara perps leverage -s ${symbol} -l ${requestedLev}`);
2091
+ }
1973
2092
  const isBuy = side === 'buy';
1974
- const slippagePx = isBuy ? entryPrice * 1.01 : entryPrice * 0.99;
2093
+ // Slippage bound from the live mark price (not the AI's entry price)
2094
+ const slippagePx = isBuy ? markPx * 1.01 : markPx * 0.99;
1975
2095
  const order = {
1976
2096
  a: symbol,
1977
2097
  b: isBuy,
1978
2098
  p: slippagePx.toPrecision(5),
1979
2099
  s: String(size),
1980
2100
  r: false,
1981
- t: { trigger: { triggerPx: String(entryPrice), tpsl: 'tp', isMarket: true } },
2101
+ t: { trigger: { triggerPx: String(markPx), tpsl: 'tp', isMarket: true } },
1982
2102
  };
1983
- await requireTransactionConfirmation(`Perps ${isBuy ? 'LONG' : 'SHORT'} ${symbol} · size ${size} @ ~$${entryPrice.toLocaleString()}`);
2103
+ await requireTransactionConfirmation(`Perps ${isBuy ? 'LONG' : 'SHORT'} ${symbol} · size ${size} @ Market (~$${markPx.toLocaleString()})`, undefined, {
2104
+ side: isBuy ? 'buy' : 'sell',
2105
+ extra: [
2106
+ ['Wallet', walletText(orderWallet)],
2107
+ ['Size', `${size} ${symbol} (~${fmt(size * markPx)} notional)`],
2108
+ ['Leverage', walletLevLabel],
2109
+ ],
2110
+ });
1984
2111
  await requireTouchId();
1985
2112
  const orderSpin = spinner('Placing order…');
1986
2113
  const orderRes = await perpsApi.placeOrders(creds.accessToken, { orders: [order], grouping: 'na', subAccountId: orderWalletId });
@@ -1989,6 +2116,40 @@ const askCmd = new Command('ask')
1989
2116
  success(`Order submitted on ${getSubAccountLabel(orderWallet)}!`);
1990
2117
  printTxResult(orderRes.data);
1991
2118
  }));
2119
+ /** Max allowed gap between the AI entry price and the live mark price for a quick order. */
2120
+ const QUICK_ORDER_MAX_DEVIATION = 0.02;
2121
+ /**
2122
+ * Turn an AI recommendation into a bounded market order plan:
2123
+ * - requires a live mark price (the order executes at market),
2124
+ * - refuses when the AI entry is more than 2% away from it,
2125
+ * - caps size at margin × leverage / mark price (AI size can only go lower),
2126
+ * - floors size to the asset's size decimals.
2127
+ */
2128
+ export function buildQuickOrderPlan(rec, meta, marginUSD, leverage) {
2129
+ const markPx = meta?.markPx;
2130
+ if (!markPx || !Number.isFinite(markPx) || markPx <= 0) {
2131
+ return { error: 'Could not fetch the current market price — quick order disabled.' };
2132
+ }
2133
+ const deviation = Math.abs(rec.entryPrice - markPx) / markPx;
2134
+ if (!Number.isFinite(deviation) || deviation > QUICK_ORDER_MAX_DEVIATION) {
2135
+ return {
2136
+ error: `AI entry ~$${rec.entryPrice.toLocaleString()} is ${(deviation * 100).toFixed(1)}% away from the current price ~$${markPx.toLocaleString()} — quick order disabled.`,
2137
+ };
2138
+ }
2139
+ if (!(marginUSD > 0) || !(leverage > 0)) {
2140
+ return { error: 'Margin and leverage must be positive numbers.' };
2141
+ }
2142
+ const maxSize = (marginUSD * leverage) / markPx;
2143
+ const capped = rec.size > maxSize;
2144
+ const raw = Math.min(rec.size, maxSize);
2145
+ const decimals = meta?.szDecimals ?? 4;
2146
+ const factor = 10 ** decimals;
2147
+ const size = Math.floor(raw * factor) / factor;
2148
+ if (!(size > 0)) {
2149
+ return { error: 'Resulting position size is too small for this asset.' };
2150
+ }
2151
+ return { markPx, size, capped };
2152
+ }
1992
2153
  /** Try to extract a tradeable recommendation from the AI analysis response. */
1993
2154
  function extractRecommendation(data, symbol, marginUSD, leverage) {
1994
2155
  if (typeof data === 'string') {
@@ -225,7 +225,7 @@ const subscribeCmd = new Command('subscribe')
225
225
  console.log(` Price : ${chalk.bold(priceStr)}`);
226
226
  console.log(` Payment : ${payMethod === 'stripe' ? 'Credit Card (Stripe)' : 'Crypto (USDC)'}`);
227
227
  console.log('');
228
- const ok = await confirm({ message: 'Proceed to checkout?', default: true });
228
+ const ok = await confirm({ message: 'Proceed to checkout?', default: false });
229
229
  if (!ok) {
230
230
  console.log(chalk.dim('Cancelled.'));
231
231
  return;
@@ -4,7 +4,7 @@ import chalk from 'chalk';
4
4
  import { swaps, swapsSimulate } from '../api/crosschain.js';
5
5
  import { get } from '../api/client.js';
6
6
  import { requireAuth } from '../config.js';
7
- import { success, info, warn, spinner, assertApiOk, wrapAction, requireTransactionConfirmation, lookupToken, normalizeChain } from '../utils.js';
7
+ import { success, info, warn, spinner, assertApiOk, wrapAction, requireTransactionConfirmation, lookupToken, normalizeChain, assertTokenOnChain } from '../utils.js';
8
8
  import { requireTouchId } from '../touchid.js';
9
9
  import { printTxResult, printSwapSimulation } from '../formatters.js';
10
10
  export const swapCommand = new Command('swap')
@@ -24,8 +24,11 @@ export const swapCommand = new Command('swap')
24
24
  throw new Error('Amount must be a positive number');
25
25
  }
26
26
  }
27
+ if (opts.side !== undefined && !['buy', 'sell'].includes(String(opts.side).toLowerCase())) {
28
+ throw new Error(`Invalid side: ${opts.side}. Must be "buy" or "sell".`);
29
+ }
27
30
  // ── 1. Side ──────────────────────────────────────────────────────────
28
- let side = opts.side;
31
+ let side = opts.side ? String(opts.side).toLowerCase() : opts.side;
29
32
  if (!side) {
30
33
  side = await select({
31
34
  message: 'Action:',
@@ -47,7 +50,10 @@ export const swapCommand = new Command('swap')
47
50
  warn(`Unsupported chain: ${opts.chain}`);
48
51
  return;
49
52
  }
50
- if (!chain) {
53
+ if (chain) {
54
+ assertTokenOnChain(tokenInfo, chain);
55
+ }
56
+ else {
51
57
  chain = normalizeChain(tokenInfo.chain);
52
58
  }
53
59
  if (!chain) {
@@ -111,6 +117,30 @@ export const swapCommand = new Command('swap')
111
117
  }
112
118
  return;
113
119
  }
120
+ // ── 6. Quote preview ─────────────────────────────────────────────────
121
+ // Show expected output, fees, slippage and price impact before the user
122
+ // approves, instead of only echoing their own input back.
123
+ if (!opts.yes) {
124
+ const quoteSpin = spinner('Fetching quote…');
125
+ let quoteShown = false;
126
+ try {
127
+ const quoteRes = await swapsSimulate(creds.accessToken, [{
128
+ chain, side, tokenAddress: tokenInfo.address, buyUsdAmountOrSellTokenAmount: amount,
129
+ }]);
130
+ quoteSpin.stop();
131
+ if (quoteRes?.success && Array.isArray(quoteRes.data) && quoteRes.data.length > 0) {
132
+ for (const item of quoteRes.data)
133
+ printSwapSimulation(item);
134
+ quoteShown = true;
135
+ }
136
+ }
137
+ catch {
138
+ quoteSpin.stop();
139
+ }
140
+ if (!quoteShown) {
141
+ warn('Could not fetch a quote — expected output, fees and slippage are unknown.');
142
+ }
143
+ }
114
144
  // ── 7. Confirm & Touch ID ──────────────────────────────────────────
115
145
  if (!opts.yes) {
116
146
  await requireTransactionConfirmation(`${side.toUpperCase()} swap · ${amount} ${side === 'buy' ? 'USD' : 'tokens'} · ${chain}`, tokenInfo, { chain, side, amount: `${amount} ${side === 'buy' ? 'USD' : '(token)'}` });
@@ -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')
@@ -22,23 +22,25 @@ export const transferCommand = new Command('transfer')
22
22
  throw new Error('Amount must be a positive number');
23
23
  }
24
24
  }
25
+ const chainOpt = opts.chain ? parseChainOption(opts.chain) : undefined;
25
26
  if (opts.to) {
26
- if (!opts.chain) {
27
+ if (!chainOpt) {
27
28
  throw new Error('--chain is required when --to is provided');
28
29
  }
29
- const addrValidation = validateAddress(opts.to, opts.chain);
30
+ const addrValidation = validateAddress(opts.to, chainOpt);
30
31
  if (addrValidation !== true) {
31
32
  throw new Error(addrValidation);
32
33
  }
33
34
  }
34
35
  // ── 1. Chain ─────────────────────────────────────────────────────────
35
- const chain = opts.chain ?? await selectChain();
36
+ const chain = chainOpt ?? await selectChain();
36
37
  // ── 2. Token ─────────────────────────────────────────────────────────
37
38
  const tokenInput = opts.token ?? await input({
38
39
  message: 'Token (address or ticker, native = 0x0…0):',
39
40
  validate: (v) => (v.length > 0 ? true : 'Token is required'),
40
41
  });
41
42
  const tokenInfo = await lookupToken(tokenInput);
43
+ assertTokenOnChain(tokenInfo, chain);
42
44
  // ── 3. Amount ────────────────────────────────────────────────────────
43
45
  const amount = opts.amount ?? await input({
44
46
  message: 'Amount to send:',
@@ -48,10 +50,10 @@ export const transferCommand = new Command('transfer')
48
50
  },
49
51
  });
50
52
  // ── 4. Recipient ─────────────────────────────────────────────────────
51
- const recipient = opts.to ?? await input({
53
+ const recipient = (opts.to ?? await input({
52
54
  message: 'Recipient address:',
53
55
  validate: (v) => validateAddress(v, chain),
54
- });
56
+ })).trim();
55
57
  // ── 5. Confirm & Touch ID ──────────────────────────────────────────
56
58
  if (!opts.yes) {
57
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')
@@ -22,11 +22,12 @@ export const withdrawCommand = new Command('withdraw')
22
22
  throw new Error('Amount must be a positive number');
23
23
  }
24
24
  }
25
+ const chainOpt = opts.chain ? parseChainOption(opts.chain) : undefined;
25
26
  if (opts.to) {
26
- if (!opts.chain) {
27
+ if (!chainOpt) {
27
28
  throw new Error('--chain is required when --to is provided');
28
29
  }
29
- const addrValidation = validateAddress(opts.to, opts.chain);
30
+ const addrValidation = validateAddress(opts.to, chainOpt);
30
31
  if (addrValidation !== true) {
31
32
  throw new Error(addrValidation);
32
33
  }
@@ -42,9 +43,9 @@ export const withdrawCommand = new Command('withdraw')
42
43
  console.log('');
43
44
  console.log(chalk.dim('Your current assets:'));
44
45
  for (const asset of assets.slice(0, 15)) {
45
- const sym = asset.symbol ?? asset.tokenSymbol ?? '';
46
- const bal = asset.balance ?? asset.amount ?? '';
47
- const ch = asset.chain ?? asset.chainName ?? '';
46
+ const sym = sanitizeTerminal(asset.symbol ?? asset.tokenSymbol ?? '');
47
+ const bal = sanitizeTerminal(asset.balance ?? asset.amount ?? '');
48
+ const ch = sanitizeTerminal(asset.chain ?? asset.chainName ?? '');
48
49
  if (sym || bal) {
49
50
  console.log(chalk.dim(` ${sym} ${bal} (${ch})`));
50
51
  }
@@ -57,13 +58,14 @@ export const withdrawCommand = new Command('withdraw')
57
58
  }
58
59
  }
59
60
  // ── 2. Chain ─────────────────────────────────────────────────────────
60
- const chain = opts.chain ?? await selectChain('Withdraw on which blockchain?');
61
+ const chain = chainOpt ?? await selectChain('Withdraw on which blockchain?');
61
62
  // ── 3. Token ─────────────────────────────────────────────────────────
62
63
  const tokenInput = opts.token ?? await input({
63
64
  message: `Token on ${chalk.cyan(chain)} (address or ticker, native = ${'0x' + '0'.repeat(40)}):`,
64
65
  validate: (v) => (v.length > 0 ? true : 'Token is required'),
65
66
  });
66
67
  const tokenInfo = await lookupToken(tokenInput);
68
+ assertTokenOnChain(tokenInfo, chain);
67
69
  // ── 4. Amount ────────────────────────────────────────────────────────
68
70
  const amount = opts.amount ?? await input({
69
71
  message: 'Amount to withdraw:',
@@ -73,10 +75,10 @@ export const withdrawCommand = new Command('withdraw')
73
75
  },
74
76
  });
75
77
  // ── 5. Destination ───────────────────────────────────────────────────
76
- const recipient = opts.to ?? await input({
78
+ const recipient = (opts.to ?? await input({
77
79
  message: 'Destination address (your external wallet):',
78
80
  validate: (v) => validateAddress(v, chain),
79
- });
81
+ })).trim();
80
82
  // ── 6. Confirm & Touch ID ──────────────────────────────────────────
81
83
  if (!opts.yes) {
82
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();