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.
@@ -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;
@@ -957,12 +975,23 @@ const closeCmd = new Command('close')
957
975
  success(`Position closed — ${sideLabel} ${symbol} ${sz}`);
958
976
  printTxResult(orderRes.data);
959
977
  }));
960
- // ─── leverage ────────────────────────────────────────────────────────────
961
978
  const leverageCmd = new Command('leverage')
962
979
  .description('Update leverage for a symbol')
963
980
  .option(WALLET_OPT[0], WALLET_OPT[1])
981
+ .option('-s, --symbol <TOKEN>', 'Target token symbol (e.g. ETH, SOL, BTC)')
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)')
964
985
  .action(wrapAction(async (opts) => {
965
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
+ }
966
995
  const resolved = await resolveWallet(creds.accessToken, opts.wallet, 'Update leverage on which wallet?');
967
996
  if (!resolved)
968
997
  return;
@@ -970,8 +999,18 @@ const leverageCmd = new Command('leverage')
970
999
  const metaSpin = spinner('Fetching available assets…');
971
1000
  const assets = await perpsApi.getAssetMeta();
972
1001
  metaSpin.stop();
1002
+ // Validate symbol if provided via CLI
973
1003
  let symbol;
974
- if (assets.length > 0) {
1004
+ if (opts.symbol) {
1005
+ symbol = opts.symbol.toUpperCase();
1006
+ const assetMeta = assets.find((a) => a.name.toUpperCase() === symbol);
1007
+ if (!assetMeta) {
1008
+ const validSymbols = assets.map((a) => a.name).join(', ');
1009
+ console.error(chalk.red('✖'), `Invalid symbol: ${opts.symbol}. Supported: ${validSymbols}`);
1010
+ process.exit(1);
1011
+ }
1012
+ }
1013
+ else if (assets.length > 0) {
975
1014
  symbol = await select({
976
1015
  message: 'Asset:',
977
1016
  choices: assets.map((a) => {
@@ -988,19 +1027,58 @@ const leverageCmd = new Command('leverage')
988
1027
  }
989
1028
  const meta = assets.find((a) => a.name.toUpperCase() === symbol.toUpperCase());
990
1029
  const maxLev = meta?.maxLeverage ?? 50;
991
- const leverage = await numberPrompt({
992
- message: `Leverage (1–${maxLev}x):`,
993
- min: 1,
994
- max: maxLev,
995
- required: true,
996
- });
997
- const isCross = await select({
998
- message: 'Margin mode:',
999
- choices: [
1000
- { name: 'Cross', value: true },
1001
- { name: 'Isolated', value: false },
1002
- ],
1003
- });
1030
+ // Validate and parse leverage
1031
+ let leverage;
1032
+ if (opts.leverage) {
1033
+ leverage = parseFloat(opts.leverage);
1034
+ if (isNaN(leverage) || leverage < 1) {
1035
+ console.error(chalk.red('✖'), `Invalid leverage: ${opts.leverage}. Must be a number >= 1.`);
1036
+ process.exit(1);
1037
+ }
1038
+ if (leverage > maxLev) {
1039
+ console.error(chalk.red('✖'), `Leverage ${leverage}x exceeds maximum ${maxLev}x for ${symbol}.`);
1040
+ process.exit(1);
1041
+ }
1042
+ }
1043
+ else {
1044
+ leverage = await numberPrompt({
1045
+ message: `Leverage (1–${maxLev}x):`,
1046
+ min: 1,
1047
+ max: maxLev,
1048
+ required: true,
1049
+ });
1050
+ }
1051
+ // Determine margin mode (cross vs isolated)
1052
+ // Explicit --margin wins; in non-interactive mode with both symbol and
1053
+ // leverage, default to cross margin (shown in the confirmation below).
1054
+ let isCross;
1055
+ if (marginFlag !== undefined) {
1056
+ isCross = marginFlag;
1057
+ }
1058
+ else if (opts.symbol && opts.leverage) {
1059
+ isCross = true;
1060
+ }
1061
+ else {
1062
+ isCross = await select({
1063
+ message: 'Margin mode:',
1064
+ choices: [
1065
+ { name: 'Cross', value: true },
1066
+ { name: 'Isolated', value: false },
1067
+ ],
1068
+ });
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();
1004
1082
  const spin = spinner('Updating leverage…');
1005
1083
  const res = await perpsApi.updateLeverage(creds.accessToken, { symbol, isCross, leverage: leverage, subAccountId: walletId });
1006
1084
  spin.stop();
@@ -1258,6 +1336,15 @@ const autopilotCmd = new Command('autopilot')
1258
1336
  break;
1259
1337
  case 'on':
1260
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();
1261
1348
  const spin = spinner('Enabling autopilot…');
1262
1349
  const res = await perpsApi.enableStrategy(creds.accessToken, state.strategyId);
1263
1350
  spin.stop();
@@ -1286,6 +1373,15 @@ const autopilotCmd = new Command('autopilot')
1286
1373
  default: state.symbols?.join(',') ?? '',
1287
1374
  });
1288
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();
1289
1385
  const spin = spinner('Updating symbols…');
1290
1386
  const res = await perpsApi.updateStrategy(creds.accessToken, {
1291
1387
  strategyId: state.strategyId,
@@ -1321,6 +1417,14 @@ const autopilotCmd = new Command('autopilot')
1321
1417
  warn('Invalid JSON. Config not updated.');
1322
1418
  break;
1323
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();
1324
1428
  const spin = spinner('Updating config…');
1325
1429
  const res = await perpsApi.updateStrategy(creds.accessToken, {
1326
1430
  strategyId: state.strategyId,
@@ -1389,6 +1493,14 @@ async function createNewStrategy(token, supported, walletId, wallet) {
1389
1493
  catch {
1390
1494
  warn('Invalid JSON — using default config.');
1391
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();
1392
1504
  const spin = spinner('Creating autopilot strategy…');
1393
1505
  const res = await perpsApi.createStrategy(token, {
1394
1506
  symbols,
@@ -1882,8 +1994,25 @@ const askCmd = new Command('ask')
1882
1994
  const { interval, hours } = styleConfig[style] ?? styleConfig['day-trading'];
1883
1995
  const endTime = Date.now();
1884
1996
  const startTime = endTime - hours * 60 * 60 * 1000;
1885
- const marginInput = await input({ message: 'Margin in USD:', default: '1000' });
1886
- 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
+ });
1887
2016
  const spin = spinner(`Analyzing ${symbol}…`);
1888
2017
  const res = await perpsApi.priceAnalysis(creds.accessToken, {
1889
2018
  symbol,
@@ -1903,7 +2032,8 @@ const askCmd = new Command('ask')
1903
2032
  console.log(chalk.bold(`AI Analysis — ${symbol} (${style}):`));
1904
2033
  console.log('');
1905
2034
  if (typeof data === 'string') {
1906
- console.log(data);
2035
+ // AI output is untrusted: keep line breaks, drop terminal control sequences
2036
+ console.log(sanitizeTerminal(data, { multiline: true }));
1907
2037
  }
1908
2038
  else {
1909
2039
  printKV(data);
@@ -1914,10 +2044,24 @@ const askCmd = new Command('ask')
1914
2044
  const recommendation = extractRecommendation(data, symbol, Number(marginInput), Number(leverageInput));
1915
2045
  if (!recommendation)
1916
2046
  return;
1917
- 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;
1918
2059
  const sideLabel = side === 'buy' ? chalk.green.bold('LONG') : chalk.red.bold('SHORT');
1919
2060
  console.log(chalk.bold('Quick Order:'));
1920
- 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
+ }
1921
2065
  console.log('');
1922
2066
  const doQuick = await confirm({ message: 'Place this order now?', default: false });
1923
2067
  if (!doQuick)
@@ -1936,17 +2080,34 @@ const askCmd = new Command('ask')
1936
2080
  info('Turn off autopilot first: minara perps autopilot');
1937
2081
  return;
1938
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
+ }
1939
2092
  const isBuy = side === 'buy';
1940
- 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;
1941
2095
  const order = {
1942
2096
  a: symbol,
1943
2097
  b: isBuy,
1944
2098
  p: slippagePx.toPrecision(5),
1945
2099
  s: String(size),
1946
2100
  r: false,
1947
- t: { trigger: { triggerPx: String(entryPrice), tpsl: 'tp', isMarket: true } },
2101
+ t: { trigger: { triggerPx: String(markPx), tpsl: 'tp', isMarket: true } },
1948
2102
  };
1949
- 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
+ });
1950
2111
  await requireTouchId();
1951
2112
  const orderSpin = spinner('Placing order…');
1952
2113
  const orderRes = await perpsApi.placeOrders(creds.accessToken, { orders: [order], grouping: 'na', subAccountId: orderWalletId });
@@ -1955,6 +2116,40 @@ const askCmd = new Command('ask')
1955
2116
  success(`Order submitted on ${getSubAccountLabel(orderWallet)}!`);
1956
2117
  printTxResult(orderRes.data);
1957
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
+ }
1958
2153
  /** Try to extract a tradeable recommendation from the AI analysis response. */
1959
2154
  function extractRecommendation(data, symbol, marginUSD, leverage) {
1960
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;
@@ -288,81 +288,6 @@ async function handleCryptoCheckout(token, planId) {
288
288
  printKV(data);
289
289
  }
290
290
  }
291
- // ─── buy-credits ────────────────────────────────────────────────────────
292
- const buyCreditsCmd = new Command('buy-credits')
293
- .description('Buy a one-time credit package')
294
- .action(wrapAction(async () => {
295
- const creds = requireAuth();
296
- const spin = spinner('Fetching packages…');
297
- const plansRes = await paymentApi.getPlans();
298
- spin.stop();
299
- assertApiOk(plansRes, 'Failed to fetch packages');
300
- const { packages } = plansRes.data;
301
- if (packages.length === 0) {
302
- info('No credit packages available.');
303
- return;
304
- }
305
- // Select package
306
- const selectedPkgId = await select({
307
- message: 'Select a credit package:',
308
- choices: packages.map((pkg) => ({
309
- name: `$${pkg.amount} — ${Number(pkg.credit).toLocaleString()} credits`,
310
- value: pkg._id,
311
- })),
312
- });
313
- const selectedPkg = packages.find((p) => p._id === selectedPkgId);
314
- // Select payment method
315
- const payMethod = await select({
316
- message: 'Payment method:',
317
- choices: [
318
- { name: 'Credit Card (Stripe)', value: 'stripe' },
319
- { name: 'Crypto (USDC on-chain)', value: 'crypto' },
320
- ],
321
- });
322
- console.log('');
323
- console.log(chalk.bold('Package Summary:'));
324
- console.log(` Price : ${chalk.bold('$' + selectedPkg.amount)}`);
325
- console.log(` Credits : ${Number(selectedPkg.credit).toLocaleString()}`);
326
- console.log(` Payment : ${payMethod === 'stripe' ? 'Credit Card (Stripe)' : 'Crypto (USDC)'}`);
327
- console.log('');
328
- const ok = await confirm({ message: 'Proceed to checkout?', default: true });
329
- if (!ok) {
330
- console.log(chalk.dim('Cancelled.'));
331
- return;
332
- }
333
- if (payMethod === 'stripe') {
334
- const spin2 = spinner('Creating checkout session…');
335
- const res = await paymentApi.checkoutPackage(creds.accessToken, selectedPkgId, 'https://minara.ai/payment/success', 'https://minara.ai/payment/cancel');
336
- spin2.stop();
337
- assertApiOk(res, 'Failed to create checkout');
338
- const url = res.data?.url ?? res.data?.checkoutUrl;
339
- if (url) {
340
- success('Opening browser for payment…');
341
- console.log(chalk.cyan(` ${url}`));
342
- openBrowser(url);
343
- }
344
- else {
345
- success('Checkout created:');
346
- printKV(res.data);
347
- }
348
- }
349
- else {
350
- const spin2 = spinner('Creating crypto checkout…');
351
- const res = await paymentApi.cryptoCheckoutPackage(creds.accessToken, selectedPkgId);
352
- spin2.stop();
353
- assertApiOk(res, 'Failed to create crypto checkout');
354
- const url = res.data?.url ?? res.data?.checkoutUrl;
355
- if (url) {
356
- success('Opening browser for crypto payment…');
357
- console.log(chalk.cyan(` ${url}`));
358
- openBrowser(url);
359
- }
360
- else {
361
- success('Crypto checkout:');
362
- printKV(res.data);
363
- }
364
- }
365
- }));
366
291
  // ─── cancel ─────────────────────────────────────────────────────────────
367
292
  const cancelCmd = new Command('cancel')
368
293
  .description('Cancel your current subscription')
@@ -398,7 +323,6 @@ export const premiumCommand = new Command('premium')
398
323
  .addCommand(plansCmd)
399
324
  .addCommand(statusCmd)
400
325
  .addCommand(subscribeCmd)
401
- .addCommand(buyCreditsCmd)
402
326
  .addCommand(cancelCmd)
403
327
  .action(wrapAction(async () => {
404
328
  const action = await select({
@@ -407,7 +331,6 @@ export const premiumCommand = new Command('premium')
407
331
  { name: 'View available plans', value: 'plans' },
408
332
  { name: 'View my subscription', value: 'status' },
409
333
  { name: 'Subscribe / Change plan', value: 'subscribe' },
410
- { name: 'Buy credit package', value: 'buy-credits' },
411
334
  { name: 'Cancel subscription', value: 'cancel' },
412
335
  ],
413
336
  });
@@ -4,20 +4,31 @@ 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
- import { printTxResult, printKV } from '../formatters.js';
9
+ import { printTxResult, printSwapSimulation } from '../formatters.js';
10
10
  export const swapCommand = new Command('swap')
11
11
  .description('Swap tokens (cross-chain spot trading)')
12
12
  .option('-s, --side <side>', 'buy or sell')
13
13
  .option('-t, --token <address|ticker>', 'Token contract address or ticker symbol')
14
14
  .option('-a, --amount <amount>', 'USD amount (buy) or token amount (sell)')
15
+ .option('-c, --chain <chain>', 'Blockchain (ethereum, base, solana, etc.)')
15
16
  .option('-y, --yes', 'Skip confirmation')
16
17
  .option('--dry-run', 'Simulate without executing')
17
18
  .action(wrapAction(async (opts) => {
18
19
  const creds = requireAuth();
20
+ // ── 0. Validate CLI options early ────────────────────────────────────
21
+ if (opts.amount) {
22
+ const amountNum = parseFloat(opts.amount);
23
+ if (opts.amount.toLowerCase() !== 'all' && (isNaN(amountNum) || amountNum <= 0)) {
24
+ throw new Error('Amount must be a positive number');
25
+ }
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
+ }
19
30
  // ── 1. Side ──────────────────────────────────────────────────────────
20
- let side = opts.side;
31
+ let side = opts.side ? String(opts.side).toLowerCase() : opts.side;
21
32
  if (!side) {
22
33
  side = await select({
23
34
  message: 'Action:',
@@ -33,10 +44,20 @@ export const swapCommand = new Command('swap')
33
44
  validate: (v) => (v.length > 0 ? true : 'Please enter a token address or ticker'),
34
45
  });
35
46
  const tokenInfo = await lookupToken(tokenInput);
36
- // ── 3. Chain (derived from token) ────────────────────────────────────
37
- const chain = normalizeChain(tokenInfo.chain);
47
+ // ── 3. Chain (use explicit flag or derive from token) ────────────────
48
+ let chain = opts.chain ? normalizeChain(opts.chain) : undefined;
49
+ if (opts.chain && !chain) {
50
+ warn(`Unsupported chain: ${opts.chain}`);
51
+ return;
52
+ }
53
+ if (chain) {
54
+ assertTokenOnChain(tokenInfo, chain);
55
+ }
56
+ else {
57
+ chain = normalizeChain(tokenInfo.chain);
58
+ }
38
59
  if (!chain) {
39
- warn(`Unable to determine chain for token. Raw chain value: ${tokenInfo.chain ?? 'unknown'}`);
60
+ warn('Unable to determine chain. Use --chain to specify.');
40
61
  return;
41
62
  }
42
63
  // ── 4. Amount ────────────────────────────────────────────────────────
@@ -89,19 +110,37 @@ export const swapCommand = new Command('swap')
89
110
  }]);
90
111
  spin.stop();
91
112
  assertApiOk(simRes, 'Simulation failed');
92
- console.log('');
93
- console.log(chalk.bold('Simulation Result:'));
94
- if (Array.isArray(simRes.data)) {
113
+ if (simRes.data && Array.isArray(simRes.data)) {
95
114
  for (const item of simRes.data) {
96
- printKV(item);
97
- console.log('');
115
+ printSwapSimulation(item);
98
116
  }
99
117
  }
100
- else if (simRes.data) {
101
- printKV(simRes.data);
102
- }
103
118
  return;
104
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
+ }
105
144
  // ── 7. Confirm & Touch ID ──────────────────────────────────────────
106
145
  if (!opts.yes) {
107
146
  await requireTransactionConfirmation(`${side.toUpperCase()} swap · ${amount} ${side === 'buy' ? 'USD' : 'tokens'} · ${chain}`, tokenInfo, { chain, side, amount: `${amount} ${side === 'buy' ? 'USD' : '(token)'}` });