Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,11 @@ minara perps order # Interactive: symbol → side → size → c
minara perps order --wallet Bot-1 # Place order on a specific wallet
minara perps close # Close a position: pick from list → market close
minara perps close --all # Close all positions at once
```

> **Market orders:** `perps order -T market`, `perps close` and the `perps ask` quick order are sent as immediate-or-cancel (IOC) limit orders, priced 1% beyond the mark price (or at `--price` if you pass one). They fill immediately or are cancelled. They never sit as a pending trigger. The old `--tpsl` flag is no longer accepted.

```bash
minara perps cancel # Cancel an order: pick from open orders list
minara perps leverage # Interactive: shows max leverage per asset
minara perps leverage -s ETH -l 5 --margin isolated # Non-interactive (asks for confirmation)
Expand Down Expand Up @@ -357,7 +362,7 @@ minara config # Select "Touch ID" to enable / disable

**Protected operations:** `withdraw`, `send` / `transfer`, `swap`, `receive` / `deposit` (Spot→Perps transfer), `perps deposit`, `perps withdraw`, `perps order`, `perps close`, `perps sweep`, `perps transfer`, `perps leverage`, `perps autopilot` (enable / update / create), `limit-order create`

> **Note:** Touch ID requires macOS with Touch ID hardware. The `--yes` flag does **not** bypass Touch ID. If Touch ID is enabled in your config but the current machine cannot use it (e.g. Linux), fund operations are cancelled instead of silently skipping the check.
> **Note:** Touch ID requires macOS with Touch ID hardware. The `--yes` flag does **not** bypass Touch ID. If Touch ID is enabled in your config but the current machine cannot use it (e.g. Linux), fund operations are cancelled instead of silently skipping the check. While Touch ID is on, turning off Touch ID or transaction confirmation in `minara config` also requires Touch ID verification.

## Supported Chains

Expand Down Expand Up @@ -385,7 +390,7 @@ minara --help

## Testing

Test suite built with [Vitest](https://vitest.dev/) — 343 tests covering unit, API, command integration, and formatter layers.
Test suite built with [Vitest](https://vitest.dev/) — 362 tests covering unit, API, command integration, and formatter layers.

```bash
npm test # Run all tests
Expand All @@ -397,7 +402,7 @@ npm run test:coverage # With v8 coverage report

- **Transaction Confirmation** — Mandatory second confirmation before all fund operations, showing full token details and contract addresses (default: enabled, configurable)
- **Touch ID** — Optional biometric protection for all fund operations (macOS only). A native Swift helper binary is compiled on first use and cached in `~/.minara/`
- **Token Verification** — Token ticker, name, and full contract address are always displayed before any transaction to prevent wrong-token mistakes
- **Token Verification** — Token ticker, name, and full contract address are always displayed before any transaction to prevent wrong-token mistakes. `$TICKER` lookups require an exact symbol match. When you have already chosen a chain (or passed `--chain`), only tokens on that chain are offered. If several tokens share a symbol, the picker shows each one's full contract address and market cap, lists the highest market cap first, and warns about same-chain lookalikes. Third-party token names are length-capped and stripped of control characters
- **Trusted API host only** — requests (including the session token and email login codes) are only sent to `https://*.minara.ai` or localhost; any other configured base URL is refused
- **Safe terminal output** — token names / symbols, API messages and chat output are stripped of terminal control sequences before display, so third-party metadata cannot rewrite or spoof confirmation screens
- **Re-login safety** — after an expired session, the original request is only retried if you sign back in to the same account
Expand Down
728 changes: 344 additions & 384 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

20 changes: 19 additions & 1 deletion src/commands/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,25 @@ import { input, select, confirm } from '@inquirer/prompts';
import chalk from 'chalk';
import { loadConfig, saveConfig, getMinaraDir, DEFAULT_BASE_URL } from '../config.js';
import { success, info, warn, wrapAction, sanitizeTerminal } from '../utils.js';
import { isTouchIdAvailable } from '../touchid.js';
import { platform } from 'node:os';
import { isTouchIdAvailable, requireTouchId } from '../touchid.js';
import { isTrustedBaseUrl } from '../api/client.js';

/**
* Turning off Touch ID or transaction confirmation lowers the protection on
* fund operations, so it must be approved with Touch ID when Touch ID is
* active on this Mac (M-250 / M-254 / M-278). On other platforms Touch ID
* cannot run (fund operations already fail closed there), so the user must
* still be able to switch it off.
*
* `requireTouchId()` exits the process if verification fails or is cancelled.
*/
async function approveLoweringProtection(touchIdEnabled: boolean | undefined): Promise<void> {
if (!touchIdEnabled || platform() !== 'darwin') return;
info('Touch ID is enabled — verify to change this protection.');
await requireTouchId();
}

export const configCommand = new Command('config')
.description('View or update CLI configuration')
.action(wrapAction(async () => {
Expand Down Expand Up @@ -61,6 +77,7 @@ export const configCommand = new Command('config')
default: false,
});
if (disable) {
await approveLoweringProtection(config.touchId);
saveConfig({ touchId: false });
success('Touch ID protection disabled.');
}
Expand Down Expand Up @@ -103,6 +120,7 @@ export const configCommand = new Command('config')
default: false,
});
if (disable) {
await approveLoweringProtection(config.touchId);
saveConfig({ confirmBeforeTransaction: false });
success('Transaction confirmation disabled.');
warn('Fund-related operations will no longer require a second confirmation.');
Expand Down
2 changes: 1 addition & 1 deletion src/commands/limit-order.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ const createCmd = new Command('create')
message: 'Target token (contract address or ticker):',
validate: (v) => (v.length > 0 ? true : 'Required'),
});
const tokenInfo = await lookupToken(tokenInput);
const tokenInfo = await lookupToken(tokenInput, { chain });
assertTokenOnChain(tokenInfo, chain);

const priceCondition = opts.condition ?? await select({
Expand Down
55 changes: 41 additions & 14 deletions src/commands/perps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -549,8 +549,8 @@ interface OrderOpts {
reduceOnly?: boolean;
grouping?: string;
wallet?: string;
/** trigger type: tp (take profit) or sl (stop loss), for market orders only */
tpsl?: 'tp' | 'sl';
/** @deprecated market orders are IOC now; the flag is rejected if passed */
tpsl?: string;
}

const orderCmd = new Command('order')
Expand All @@ -564,10 +564,21 @@ const orderCmd = new Command('order')
.option('-z, --size <size>', 'Position size in contracts')
.option('-r, --reduce-only', 'Reduce-only order')
.option('-g, --grouping <grouping>', 'TP/SL grouping: na, normalTpsl, positionTpsl', 'na')
.option('--tpsl <type>', 'Trigger type for market orders: tp (take profit) or sl (stop loss)', 'tp')
.option('--tpsl <type>', 'Deprecated: market orders now execute immediately (IOC); passing this flag is an error')
.action(wrapAction(async (opts: OrderOpts) => {
const creds = requireAuth();

// Market orders used to be sent as TP/SL trigger orders, which only fire
// when the trigger price is crossed. They are now IOC limit orders that
// execute immediately, so --tpsl no longer means anything. Refuse it
// rather than silently turning an intended stop-loss into a market fill.
if (opts.tpsl !== undefined) {
throw new Error(
'--tpsl is no longer supported: market orders now execute immediately as IOC limit orders. '
+ 'Remove the flag, or place a limit order (-T limit -p <price>) instead.',
);
}

for (const [flag, value] of [['--price', opts.price], ['--size', opts.size]] as const) {
if (value !== undefined && !(Number(value) > 0)) {
throw new Error(`${flag} must be a positive number`);
Expand Down Expand Up @@ -774,9 +785,11 @@ const orderCmd = new Command('order')
p: limitPx,
s: sz,
r: reduceOnly,
// Market = IOC limit at the slippage-bounded price (Hyperliquid has no
// native market order type). A TP/SL trigger would not fill immediately.
t: orderType === 'limit'
? { limit: { tif: 'Gtc' } }
: { trigger: { triggerPx: String(marketPx ?? limitPx), tpsl: opts.tpsl ?? 'tp', isMarket: true } },
: { limit: { tif: 'Ioc' } },
};

const priceLabel = orderType === 'market' ? `Market (~$${marketPx ?? limitPx})` : `$${limitPx}`;
Expand All @@ -788,7 +801,7 @@ const orderCmd = new Command('order')
console.log(` Asset : ${chalk.bold(order.a)}`);
console.log(` Side : ${formatOrderSide(order.b ? 'buy' : 'sell')}`);
console.log(` Leverage : ${chalk.cyan(levLabel)}`);
console.log(` Type : ${orderType === 'market' ? `Market (${opts.tpsl === 'sl' ? 'Stop Loss' : 'Take Profit'})` : 'Limit (GTC)'}`);
console.log(` Type : ${orderType === 'market' ? 'Market (IOC)' : 'Limit (GTC)'}`);
console.log(` Price : ${chalk.yellow(priceLabel)}`);
console.log(` Size : ${chalk.bold(order.s)}`);
console.log(` Reduce Only : ${order.r ? chalk.yellow('Yes') : 'No'}`);
Expand Down Expand Up @@ -905,7 +918,9 @@ const closeCmd = new Command('close')
const assets = await perpsApi.getAssetMeta();
spin.stop();

const positions = Array.isArray(d.positions) ? d.positions as Record<string, unknown>[] : [];
// Sub-account summaries come back in Hyperliquid's raw shape
// (marginSummary + assetPositions); normalise like every other command.
const positions = normalizeWalletSummary(d).positions;

if (positions.length === 0) {
info(`No open positions on ${getSubAccountLabel(wallet)}.`);
Expand Down Expand Up @@ -964,7 +979,7 @@ const closeCmd = new Command('close')
p: limitPx,
s: sz,
r: true,
t: { trigger: { triggerPx: String(marketPx), tpsl: 'tp', isMarket: true } },
t: { limit: { tif: 'Ioc' } },
};

try {
Expand Down Expand Up @@ -1075,7 +1090,7 @@ const closeCmd = new Command('close')
p: limitPx,
s: sz,
r: true,
t: { trigger: { triggerPx: String(marketPx), tpsl: 'tp', isMarket: true } },
t: { limit: { tif: 'Ioc' } },
};

const sideLabel = isLong ? 'LONG' : 'SHORT';
Expand Down Expand Up @@ -2098,21 +2113,33 @@ const sweepCmd = new Command('sweep')
return;
}

const equity = Number(wallet.equityValue ?? 0);
if (equity <= 0) {
info('This wallet has no funds to sweep.');
// Use the live summary fetched above (not the cached list value)
const selIdx = nonDefault.findIndex((w) => getSubAccountId(w) === walletId);
const selRes = summaries[selIdx];
const live = normalizeWalletSummary(
selRes?.success && selRes.data ? selRes.data as Record<string, unknown> : wallet as Record<string, unknown>,
);
if (!(live.available > 0)) {
if (live.equity > 0) {
info(`This wallet has ${fmt(live.equity)} equity but nothing withdrawable (funds are used as margin). Close positions first.`);
} else {
info('This wallet has no funds to sweep.');
}
return;
}

console.log('');
console.log(chalk.bold('Sweep Funds:'));
console.log(` From : ${getSubAccountLabel(wallet)}`);
console.log(` To : Default wallet`);
console.log(` Amount : ${fmt(equity)} (all available)`);
console.log(` Amount : ${fmt(live.available)} (all withdrawable)`);
console.log('');

if (!opts.yes) {
await requireTransactionConfirmation(`Sweep funds from "${wallet.name}" to default wallet`);
await requireTransactionConfirmation(`Sweep funds from "${wallet.name}" to default wallet`, undefined, {
amount: `${fmt(live.available)} USDC`,
extra: [['From', walletText(wallet)], ['To', 'Default wallet']],
});
}
await requireTouchId();

Expand Down Expand Up @@ -2358,7 +2385,7 @@ const askCmd = new Command('ask')
p: slippagePx.toPrecision(5),
s: String(size),
r: false,
t: { trigger: { triggerPx: String(markPx), tpsl: 'tp', isMarket: true } },
t: { limit: { tif: 'Ioc' } },
};

await requireTransactionConfirmation(
Expand Down
4 changes: 2 additions & 2 deletions src/commands/swap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,14 @@ export const swapCommand = new Command('swap')
message: 'Token (contract address or ticker):',
validate: (v) => (v.length > 0 ? true : 'Please enter a token address or ticker'),
});
const tokenInfo = await lookupToken(tokenInput);

// ── 3. Chain (use explicit flag or derive from token) ────────────────
let chain: Chain | undefined = opts.chain ? normalizeChain(opts.chain) : undefined;
if (opts.chain && !chain) {
warn(`Unsupported chain: ${opts.chain}`);
return;
}
// With --chain, only candidates on that chain are offered
const tokenInfo = await lookupToken(tokenInput, { chain });
if (chain) {
assertTokenOnChain(tokenInfo, chain);
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/commands/transfer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export const transferCommand = new Command('transfer')
message: 'Token (address or ticker, native = 0x0…0):',
validate: (v) => (v.length > 0 ? true : 'Token is required'),
});
const tokenInfo = await lookupToken(tokenInput);
const tokenInfo = await lookupToken(tokenInput, { chain });
assertTokenOnChain(tokenInfo, chain);

// ── 3. Amount ────────────────────────────────────────────────────────
Expand Down
2 changes: 1 addition & 1 deletion src/commands/withdraw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export const withdrawCommand = new Command('withdraw')
message: `Token on ${chalk.cyan(chain)} (address or ticker, native = ${'0x' + '0'.repeat(40)}):`,
validate: (v) => (v.length > 0 ? true : 'Token is required'),
});
const tokenInfo = await lookupToken(tokenInput);
const tokenInfo = await lookupToken(tokenInput, { chain });
assertTokenOnChain(tokenInfo, chain);

// ── 4. Amount ────────────────────────────────────────────────────────
Expand Down
10 changes: 5 additions & 5 deletions src/formatters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import chalk from 'chalk';
import Table from 'cli-table3';
import type { CrossChainSwapsSimulateResultDto, CrossChainSwapsSimulateErrorDto } from './types.js';
import { sanitizeTerminal, sanitizeDeep } from './utils.js';
import { sanitizeTerminal, sanitizeDeep, cleanTokenText, TOKEN_SYMBOL_MAX, TOKEN_NAME_MAX } from './utils.js';

// ─── Wei / BigInt formatting ──────────────────────────────────────────────

Expand Down Expand Up @@ -317,7 +317,7 @@ export function printTxResult(data: unknown): void {

/** Spot wallet assets (WalletAsset[]) */
export const SPOT_COLUMNS: ColumnDef[] = [
{ key: 'tokenSymbol', label: 'Token', format: (v) => chalk.bold(String(v ?? '—')) },
{ key: 'tokenSymbol', label: 'Token', format: (v) => chalk.bold(v == null ? '—' : cleanTokenText(v, TOKEN_SYMBOL_MAX)) },
{ key: 'chainId', label: 'Chain', format: (v) => {
const s = String(v ?? '—');
return chalk.cyan(s.charAt(0).toUpperCase() + s.slice(1));
Expand Down Expand Up @@ -444,7 +444,7 @@ function compactUsd(v: unknown): string {

/** Trending / search tokens (TokenInfo[]) */
export const TOKEN_COLUMNS: ColumnDef[] = [
{ key: 'symbol', label: 'Symbol', format: (v) => chalk.bold(String(v ?? '—')) },
{ key: 'symbol', label: 'Symbol', format: (v) => chalk.bold(v == null ? '—' : cleanTokenText(v, TOKEN_SYMBOL_MAX)) },
{ key: 'chain', label: 'Chain', format: (v) => v ? chalk.cyan(String(v)) : chalk.dim('—') },
{ key: 'price', label: 'Price', format: (v) => formatValue(v, 'price') },
{ key: 'priceChange24H', label: '24h %', format: (v) => formatValue(v, 'change') },
Expand All @@ -453,8 +453,8 @@ export const TOKEN_COLUMNS: ColumnDef[] = [
];

export const STOCK_COLUMNS: ColumnDef[] = [
{ key: 'symbol', label: 'Symbol', format: (v) => chalk.bold(String(v ?? '—')) },
{ key: 'name', label: 'Name' },
{ key: 'symbol', label: 'Symbol', format: (v) => chalk.bold(v == null ? '—' : cleanTokenText(v, TOKEN_SYMBOL_MAX)) },
{ key: 'name', label: 'Name', format: (v) => (v == null ? chalk.dim('—') : cleanTokenText(v, TOKEN_NAME_MAX)) },
{ key: 'price', label: 'Price', format: (v) => formatValue(v, 'price') },
{ key: 'priceChange24H', label: '24h %', format: (v) => formatValue(v, 'change') },
{ key: 'volume24H', label: 'Volume 24h', format: compactUsd },
Expand Down
Loading