diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..7f5518b
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,49 @@
+name: CI
+
+on:
+ pull_request:
+ push:
+ branches: [main]
+
+# Read-only token; this workflow never sees secrets (pull_request, not
+# pull_request_target), so it is safe to run on pull requests from forks.
+permissions:
+ contents: read
+
+concurrency:
+ group: ci-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ node-version: ['20', '22', '24']
+ steps:
+ - name: Checkout
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+
+ - name: Setup Node.js
+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
+ with:
+ node-version: ${{ matrix.node-version }}
+ package-manager-cache: false
+
+ - name: Install dependencies
+ run: npm ci --ignore-scripts
+
+ - name: Type check
+ run: npx tsc --noEmit
+
+ - name: Run tests
+ run: npm test
+
+ - name: Build
+ run: npm run build
+
+ - name: Audit production dependencies
+ run: npm audit --omit=dev --audit-level=moderate
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index 9214e8a..d83081a 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -4,25 +4,59 @@ on:
release:
types: [published]
-permissions:
- contents: read
- id-token: write
+# Nothing at workflow level; the publish job asks only for what it needs.
+permissions: {}
jobs:
publish:
runs-on: ubuntu-latest
+ # NPM_TOKEN is an environment secret of "release", which only v* tags may
+ # deploy to, and only admins may create tags. A workflow pushed on a
+ # branch cannot read it. Optionally add required reviewers to the
+ # environment so a release also needs an explicit approval to publish.
+ environment: release
+ permissions:
+ contents: read
+ id-token: write # npm trusted publishing (OIDC) and provenance
steps:
+ # Actions are pinned to full commit SHAs (tags can be moved).
- name: Checkout
- uses: actions/checkout@v4
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
- name: Setup Node.js
- uses: actions/setup-node@v4
+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
- node-version: '20'
+ # Trusted publishing needs Node >= 22.14 and npm >= 11.5.1
+ node-version: '24'
registry-url: 'https://registry.npmjs.org'
+ # No dependency cache in the release job (cache-poisoning risk)
+ package-manager-cache: false
+
+ - name: Check npm version
+ run: |
+ node -e '
+ const [a, b, c] = process.argv[1].split(".").map(Number);
+ const ok = a > 11 || (a === 11 && (b > 5 || (b === 5 && c >= 1)));
+ if (!ok) { console.error(`::error::npm ${process.argv[1]} is too old for trusted publishing (need >= 11.5.1)`); process.exit(1); }
+ console.log(`npm ${process.argv[1]}`);
+ ' "$(npm --version)"
+
+ - name: Check release tag matches package.json
+ env:
+ TAG: ${{ github.event.release.tag_name }}
+ run: |
+ PKG="$(node -p "require('./package.json').version")"
+ if [ "${TAG#v}" != "$PKG" ]; then
+ echo "::error::Release tag $TAG does not match package.json version $PKG"
+ exit 1
+ fi
- name: Install dependencies
- run: npm ci
+ # No dependency needs install scripts; skipping them blocks a whole
+ # class of supply-chain attacks during the release build.
+ run: npm ci --ignore-scripts
- name: Run tests
run: npm test
@@ -31,6 +65,10 @@ jobs:
run: npm run build
- name: Publish to NPM
- run: npm publish
+ # Uses OIDC trusted publishing once it is configured on npmjs.com
+ # (Minara-AI / minara-cli / publish.yml / environment release);
+ # until then npm falls back to NPM_TOKEN. --provenance links the
+ # published tarball to this workflow run.
+ run: npm publish --provenance --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
diff --git a/README.md b/README.md
index f2fddc3..ac422d1 100644
--- a/README.md
+++ b/README.md
@@ -71,7 +71,7 @@ minara discover trending
| Command | Description |
| ---------------- | ------------------------------------------- |
| `minara login` | Login via device code or email |
-| `minara logout` | Logout and clear local credentials |
+| `minara logout` | Logout: revoke the session, then clear local credentials (`--local` clears them even if the server is unreachable) |
| `minara account` | View your account info and wallet addresses |
```bash
@@ -119,6 +119,7 @@ minara swap # Interactive: side → token → amount
minara swap -s buy -t '$BONK' -a 100 # Buy by ticker (chain auto-detected)
minara swap -s sell -t '$NVDAx' -a all # Sell entire balance
minara swap --dry-run # Simulate without executing
+minara swap -s buy -t '$BONK' -a 100 --max-slippage 15 # Accept a quote with up to 15% slippage tolerance
# Send tokens
minara send -c solana -t '$SOL' -a 5 --to
# Send SOL on Solana
@@ -164,7 +165,14 @@ minara perps close # Close a position: pick from list → market
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.
+> **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. After submitting, the CLI reads Hyperliquid's per-order result. It shows the filled size and average price, warns about partial fills, and exits with an error if the order was rejected (for example, no liquidity within 1%).
+
+> **Order rules:** prices and sizes follow Hyperliquid's [tick and lot sizes](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/tick-and-lot-size):
+> - a price has at most 5 significant figures and at most 6 − szDecimals decimals (whole-number prices are always allowed);
+> - a size has at most szDecimals decimals;
+> - a new order must be worth at least $10.
+>
+> Orders that break these rules are refused before anything is sent, and an invalid `--price` gets the nearest valid price as a suggestion.
```bash
minara perps cancel # Cancel an order: pick from open orders list
@@ -319,7 +327,7 @@ Available settings:
| Setting | Default | Description |
| ------------------------ | ------- | ---------------------------------------------------- |
-| Base URL | `https://api.minara.ai` | API endpoint — must be `https://*.minara.ai` (or localhost for development) |
+| Base URL | `https://api.minara.ai` | API endpoint — must be `https://*.minara.ai` (localhost only with `MINARA_DEV=1` set, for development) |
| Touch ID | Off | Biometric verification for fund operations (macOS) |
| Transaction Confirmation | **On** | Mandatory second confirmation before fund operations |
@@ -348,9 +356,9 @@ The **transaction confirmation** shows chain, token, address, side, amount, and
? Are you sure you want to proceed? (y/N)
```
-For `swap`, the expected output, fees, slippage and price impact are fetched and shown before this prompt.
+For `swap`, the expected output, fees, slippage and price impact are fetched and shown before this prompt, also with `-y`. The swap request cannot carry a minimum output, so the CLI refuses quotes whose slippage tolerance or price impact is above 10% (raise with `--max-slippage` / `--max-price-impact`). With `-y` it also refuses to swap when no quote can be fetched.
-**About `-y` / `--yes`:** on `swap`, `transfer`, `withdraw`, `deposit` (Spot → Perps), `limit-order create`, `perps order`, `perps close`, `perps sweep`, `perps transfer` and `perps leverage`, `-y` skips the transaction confirmation for scripting. `perps deposit`, `perps withdraw`, the `perps ask` quick order and autopilot changes always show it. Touch ID, when enabled, is never skipped. If you disable transaction confirmation via `minara config`, every skipped prompt prints a warning.
+**About `-y` / `--yes`:** on `swap`, `transfer`, `withdraw`, `deposit` (Spot → Perps), `limit-order create`, `limit-order cancel`, `perps order`, `perps close`, `perps cancel`, `perps sweep`, `perps transfer` and `perps leverage`, `-y` skips the transaction confirmation for scripting. `perps deposit`, `perps withdraw`, the `perps ask` quick order and autopilot changes always show it. Touch ID, when enabled, is never skipped. If you disable transaction confirmation via `minara config`, every skipped prompt prints a warning.
### Touch ID (macOS)
@@ -360,9 +368,9 @@ Minara CLI supports macOS Touch ID to protect all fund-related operations. When
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`
+**Protected operations:** `withdraw`, `send` / `transfer`, `swap`, `receive` / `deposit` (Spot→Perps transfer), `perps deposit`, `perps withdraw`, `perps order`, `perps close`, `perps cancel`, `perps sweep`, `perps transfer`, `perps leverage`, `perps autopilot` (enable / update / create), `limit-order create`, `limit-order cancel`. Cancelling counts because an order may be the stop-loss or take-profit protecting a position. `perps cancel` warns when it is.
-> **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.
+> **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. The same applies when `~/.minara/config.json` is damaged (for example truncated): fund operations are refused until it is fixed or rewritten with `minara config`. Config and credential files are written atomically. While Touch ID is on, turning off Touch ID or transaction confirmation in `minara config` also requires Touch ID verification.
## Supported Chains
@@ -390,7 +398,7 @@ minara --help
## Testing
-Test suite built with [Vitest](https://vitest.dev/) — 362 tests covering unit, API, command integration, and formatter layers.
+Test suite built with [Vitest](https://vitest.dev/) — 425 tests covering unit, API, command integration, and formatter layers.
```bash
npm test # Run all tests
@@ -403,15 +411,19 @@ 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. `$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
+- **Trusted API host only** — requests (including the session token and email login codes) are only sent to `https://*.minara.ai` (localhost only when `MINARA_DEV=1` is set); any other configured base URL is refused
+- **Safe terminal output** — every API response (including Hyperliquid market data) is stripped of terminal control sequences, C1 controls, bidi override characters and invisible characters (zero-width, soft hyphen, BOM, Unicode tags…) as it arrives. Chat output is cleaned the same way as it streams. Third-party metadata cannot rewrite or spoof confirmation screens
+- **Recipient checks** — withdraw / send addresses are validated for the chain. A Solana address must decode to a 32-byte key, and one that is not a wallet public key (off the ed25519 curve) gets a warning, because Solana addresses have no checksum
- **Re-login safety** — after an expired session, the original request is only retried if you sign back in to the same account
- Credentials are stored in `~/.minara/credentials.json` with `0600` file permissions (re-applied on every write)
- The `~/.minara/` directory is kept at `0700` permissions
- Tokens are never logged or printed to the console
-- OAuth login uses a temporary local server that shuts down after the callback
+- **Pinned dependencies** — the package ships an `npm-shrinkwrap.json`, so `npm i -g minara` installs exactly the dependency versions that were tested
+- **Release provenance** — releases are published from GitHub Actions with npm provenance, so you can check which commit and workflow built a version (`npm audit signatures`)
- Non-TTY environments (CI/pipes) skip interactive prompts and return errors directly
+> **Limits of client-side protection:** transaction confirmation and Touch ID run inside the CLI on your machine. A process that already runs as your user (including an AI agent with shell access) can edit `~/.minara/config.json`, replace files in `~/.minara/`, or modify the installed CLI, so treat these checks as protection against mistakes and misleading prompts, not against code that already controls your account on this machine. Only give agents the access they need, and prefer running them in a sandbox.
+
## License
[MIT](LICENSE)
diff --git a/package-lock.json b/npm-shrinkwrap.json
similarity index 99%
rename from package-lock.json
rename to npm-shrinkwrap.json
index e159097..03f1627 100644
--- a/package-lock.json
+++ b/npm-shrinkwrap.json
@@ -1,12 +1,12 @@
{
"name": "minara",
- "version": "0.5.1",
+ "version": "0.5.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "minara",
- "version": "0.5.1",
+ "version": "0.5.2",
"license": "MIT",
"dependencies": {
"@inquirer/prompts": "^7.0.0",
@@ -580,9 +580,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -600,9 +597,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -620,9 +614,6 @@
"ppc64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -640,9 +631,6 @@
"s390x"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -660,9 +648,6 @@
"x64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -680,9 +665,6 @@
"x64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1458,9 +1440,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MPL-2.0",
"optional": true,
"os": [
@@ -1482,9 +1461,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MPL-2.0",
"optional": true,
"os": [
@@ -1506,9 +1482,6 @@
"x64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MPL-2.0",
"optional": true,
"os": [
@@ -1530,9 +1503,6 @@
"x64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MPL-2.0",
"optional": true,
"os": [
diff --git a/package.json b/package.json
index 74ea900..052289d 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "minara",
- "version": "0.5.1",
+ "version": "0.5.2",
"description": "CLI client for Minara.ai — login, trade, deposit/withdraw, chat and more from your terminal.",
"type": "module",
"main": "dist/index.js",
@@ -10,7 +10,8 @@
},
"files": [
"dist",
- "bin"
+ "bin",
+ "npm-shrinkwrap.json"
],
"scripts": {
"build": "tsc",
diff --git a/src/api/auth.ts b/src/api/auth.ts
index cbb5d4c..b8c3f9f 100644
--- a/src/api/auth.ts
+++ b/src/api/auth.ts
@@ -26,7 +26,9 @@ export function getCurrentUser(token: string) {
/** Logout */
export function logout(token: string) {
- return post('/auth/logout', { token });
+ // An expired session must not trigger the "log in again?" flow: that would
+ // log in and then immediately revoke the new session.
+ return post('/auth/logout', { token, noReauth: true });
}
/** Get OAuth authorization URL */
diff --git a/src/api/client.ts b/src/api/client.ts
index 41c1d1f..e40d13e 100644
--- a/src/api/client.ts
+++ b/src/api/client.ts
@@ -1,5 +1,6 @@
import { loadConfig } from '../config.js';
import type { ApiResponse } from '../types.js';
+import { sanitizeDeep, sanitizeTerminal } from '../sanitize.js';
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
@@ -9,20 +10,31 @@ interface RequestOptions {
query?: Record;
token?: string;
headers?: Record;
+ /** Return a plain 401 instead of prompting to log in again (e.g. logout). */
+ noReauth?: boolean;
}
// ── Base URL trust check ──────────────────────────────────────────────────
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
+/** Loopback API hosts are only honoured when this is set (local development). */
+export const DEV_ENV_FLAG = 'MINARA_DEV';
+
+function devModeEnabled(): boolean {
+ return process.env[DEV_ENV_FLAG] === '1';
+}
+
/**
* The CLI sends the session token, email login codes and fund-moving requests
* to `baseUrl`, so it must point at a Minara-operated host.
*
- * Allowed: `https://minara.ai` and `https://*.minara.ai`, plus http/https on
- * loopback for local development. Anything else is rejected.
+ * Allowed: `https://minara.ai` and `https://*.minara.ai`. http/https on
+ * loopback is allowed only with `MINARA_DEV=1`, so a development base URL left
+ * in the config cannot hand the token to whatever later listens on that local
+ * port. Anything else is rejected.
*/
-export function isTrustedBaseUrl(raw: unknown): boolean {
+export function isTrustedBaseUrl(raw: unknown, opts: { allowLoopback?: boolean } = {}): boolean {
if (typeof raw !== 'string') return false;
let url: URL;
try {
@@ -32,13 +44,16 @@ export function isTrustedBaseUrl(raw: unknown): boolean {
}
if (url.username || url.password) return false;
const host = url.hostname.toLowerCase();
- if (LOOPBACK_HOSTS.has(host)) return url.protocol === 'https:' || url.protocol === 'http:';
+ if (LOOPBACK_HOSTS.has(host)) {
+ const allow = opts.allowLoopback ?? devModeEnabled();
+ return allow && (url.protocol === 'https:' || url.protocol === 'http:');
+ }
return url.protocol === 'https:' && (host === 'minara.ai' || host.endsWith('.minara.ai'));
}
export const UNTRUSTED_BASE_URL_MESSAGE =
'Refusing to contact the API: the base URL in ~/.minara/config.json is not a Minara host. ' +
- 'Only https://*.minara.ai (or localhost for development) is allowed. ' +
+ 'Only https://*.minara.ai is allowed (localhost only with MINARA_DEV=1 for development). ' +
'Run `minara config` → "Set base URL" to reset it.';
/**
@@ -109,21 +124,25 @@ async function requestImpl(
// ── 401 interception ──────────────────────────────────────────────
// Only trigger when: (1) authenticated request, (2) not already a retry,
// (3) running in an interactive terminal (not piped / CI).
- if (res.status === 401 && token && !isRetry) {
+ if (res.status === 401 && token && !isRetry && !opts.noReauth) {
return handleAuthExpired(path, opts);
}
const text = await res.text();
let json: unknown;
try {
- json = JSON.parse(text);
+ // Every string in a response is untrusted (token metadata, names, AI
+ // text…): strip terminal control sequences once, at the boundary, so
+ // no display path can forget. Line breaks are kept (multiline mode).
+ json = sanitizeDeep(JSON.parse(text), { multiline: true });
} catch {
// non-JSON response
+ const clean = sanitizeTerminal(text, { multiline: true });
if (!res.ok) {
- return { success: false, error: { code: res.status, message: text || res.statusText } };
+ return { success: false, error: { code: res.status, message: clean || res.statusText } };
}
// Non-JSON success response — wrap the text as data
- return { success: true, data: text as T };
+ return { success: true, data: clean as T };
}
if (!res.ok) {
diff --git a/src/api/perps.ts b/src/api/perps.ts
index 3068766..44785be 100644
--- a/src/api/perps.ts
+++ b/src/api/perps.ts
@@ -1,4 +1,5 @@
import { get, post } from './client.js';
+import { sanitizeDeep } from '../sanitize.js';
import type {
PerpsDepositDto,
PerpsWithdrawDto,
@@ -215,7 +216,7 @@ export async function getAssetMeta(): Promise {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type: 'metaAndAssetCtxs' }),
});
- const json = (await res.json()) as [
+ const json = (sanitizeDeep(await res.json())) as [
{ universe: HlAssetMeta[] },
{ markPx: string; midPx?: string }[],
];
@@ -237,17 +238,27 @@ export interface HlOpenOrder {
side: string; // 'A' (sell) or 'B' (buy)
sz: string;
timestamp: number;
-}
-
-/** Fetch user's open orders from Hyperliquid. */
+ // frontendOpenOrders extras — tell a TP/SL protecting a position apart
+ orderType?: string; // e.g. "Limit", "Stop Market", "Take Profit Limit"
+ reduceOnly?: boolean;
+ isTrigger?: boolean;
+ triggerPx?: string;
+ isPositionTpsl?: boolean;
+}
+
+/**
+ * Fetch user's open orders from Hyperliquid. Uses `frontendOpenOrders`
+ * (a superset of `openOrders`) so callers can see order type, reduce-only
+ * and trigger details.
+ */
export async function getOpenOrders(address: string): Promise {
try {
const res = await fetch('https://api.hyperliquid.xyz/info', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ type: 'openOrders', user: address }),
+ body: JSON.stringify({ type: 'frontendOpenOrders', user: address }),
});
- const data = await res.json();
+ const data = sanitizeDeep(await res.json());
return Array.isArray(data) ? data as HlOpenOrder[] : [];
} catch {
return [];
@@ -281,7 +292,7 @@ export async function getUserFills(address: string, days = 7): Promise
aggregateByTime: true,
}),
});
- const data = await res.json();
+ const data = sanitizeDeep(await res.json());
return Array.isArray(data) ? data as HlFill[] : [];
} catch {
return [];
@@ -303,7 +314,7 @@ export async function getUserLeverage(address: string): Promise {
console.log(chalk.bold(`Perps Wallets (${wallets.length}):`));
for (const w of wallets) {
- const name = String(w.name ?? 'Unnamed');
+ const name = sanitizeTerminal(w.name ?? 'Unnamed');
const def = w.isDefault ? chalk.cyan(' (default)') : '';
console.log('');
diff --git a/src/commands/config.ts b/src/commands/config.ts
index c329cb2..684aed3 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -26,6 +26,10 @@ export const configCommand = new Command('config')
.description('View or update CLI configuration')
.action(wrapAction(async () => {
const config = loadConfig();
+ if (config.loadError) {
+ warn(`Your config could not be read (${sanitizeTerminal(config.loadError)}).`);
+ warn('Fund operations are blocked until it is fixed. Saving any setting below rewrites the file with defaults plus your change.');
+ }
const confirmTx = config.confirmBeforeTransaction !== false;
const action = await select({
@@ -62,7 +66,7 @@ export const configCommand = new Command('config')
default: isTrustedBaseUrl(config.baseUrl) ? config.baseUrl : DEFAULT_BASE_URL,
validate: (v) => isTrustedBaseUrl(v)
? true
- : 'Base URL must be https://minara.ai or https://*.minara.ai (http/https on localhost allowed for development)',
+ : 'Base URL must be https://minara.ai or https://*.minara.ai (localhost needs MINARA_DEV=1 for development)',
});
saveConfig({ baseUrl: url });
success(`Base URL set to ${url}`);
diff --git a/src/commands/limit-order.ts b/src/commands/limit-order.ts
index 19427f0..51f503c 100644
--- a/src/commands/limit-order.ts
+++ b/src/commands/limit-order.ts
@@ -1,9 +1,9 @@
import { Command } from 'commander';
-import { input, select, confirm, number as numberPrompt } from '@inquirer/prompts';
+import { input, select, number as numberPrompt } from '@inquirer/prompts';
import chalk from 'chalk';
import * as loApi from '../api/limitorder.js';
import { requireAuth } from '../config.js';
-import { success, info, spinner, assertApiOk, selectChain, wrapAction, requireTransactionConfirmation, lookupToken, formatTokenLabel, parseChainOption, assertTokenOnChain } from '../utils.js';
+import { success, info, spinner, assertApiOk, selectChain, wrapAction, requireTransactionConfirmation, lookupToken, formatTokenLabel, parseChainOption, assertTokenOnChain, sanitizeTerminal } from '../utils.js';
import type { Chain } from '../types.js';
import { requireTouchId } from '../touchid.js';
import { printTxResult, printTable, LIMIT_ORDER_COLUMNS } from '../formatters.js';
@@ -95,7 +95,7 @@ const createCmd = new Command('create')
console.log(` Chain : ${chalk.cyan(chain)}`);
console.log(` Side : ${side}`);
console.log(` Token : ${formatTokenLabel(tokenInfo)}`);
- console.log(` Address : ${chalk.yellow(tokenInfo.address)}`);
+ console.log(` Address : ${chalk.yellow(sanitizeTerminal(tokenInfo.address))}`);
console.log(` Condition : price ${priceCondition} $${targetPrice}`);
console.log(` Amount : $${amount}`);
console.log(` Expires : ${new Date(expiredAt * 1000).toLocaleString()}`);
@@ -149,27 +149,46 @@ const cancelCmd = new Command('cancel')
.action(wrapAction(async (idArg?: string, opts?: { yes?: boolean }) => {
const creds = requireAuth();
+ // Fetch the list either way so the confirmation shows what is cancelled
+ const listSpin = spinner('Fetching orders…');
+ const listRes = await loApi.listLimitOrders(creds.accessToken);
+ listSpin.stop();
+ const orders = Array.isArray(listRes.data) ? listRes.data : [];
+
let id = idArg;
if (!id) {
- const spin = spinner('Fetching orders…');
- const listRes = await loApi.listLimitOrders(creds.accessToken);
- spin.stop();
- const orders = listRes.data;
- if (!orders || orders.length === 0) { info('No orders to cancel.'); return; }
-
+ if (orders.length === 0) { info('No orders to cancel.'); return; }
id = await select({
message: 'Select order to cancel:',
choices: orders.map((o) => ({
- name: `[${o.id.slice(0, 12)}…] ${o.side ?? ''} @ $${o.targetPrice ?? '?'} status=${o.status ?? '?'}`,
+ name: `[${sanitizeTerminal(o.id).slice(0, 12)}…] ${sanitizeTerminal(o.side ?? '')} @ $${sanitizeTerminal(o.targetPrice ?? '?')} status=${sanitizeTerminal(o.status ?? '?')}`,
value: o.id,
})),
});
}
+ const order = orders.find((o) => o.id === id);
+ // A limit order may be a user's stop-loss / take-profit: cancelling it
+ // gets the same confirmation and Touch ID as creating one.
if (!opts?.yes) {
- const ok = await confirm({ message: `Cancel order ${id}?`, default: false });
- if (!ok) return;
+ const extra: [string, string][] = [['Order ID', sanitizeTerminal(id)]];
+ if (order) {
+ extra.push(['Trigger', `price ${sanitizeTerminal(order.priceCondition)} $${sanitizeTerminal(order.targetPrice)}`]);
+ if (order.targetTokenCA) extra.push(['Token', sanitizeTerminal(order.targetTokenCA)]);
+ if (order.status) extra.push(['Status', sanitizeTerminal(order.status)]);
+ }
+ await requireTransactionConfirmation(
+ `Cancel limit order ${sanitizeTerminal(id)}`,
+ undefined,
+ {
+ chain: order?.chain,
+ side: order ? `cancel ${sanitizeTerminal(order.side)}` : 'cancel',
+ amount: order?.amount ? sanitizeTerminal(order.amount) : undefined,
+ extra,
+ },
+ );
}
+ await requireTouchId();
const spin = spinner('Cancelling…');
const res = await loApi.cancelLimitOrder(creds.accessToken, id!);
diff --git a/src/commands/logout.ts b/src/commands/logout.ts
index 6ab83ab..411e4f2 100644
--- a/src/commands/logout.ts
+++ b/src/commands/logout.ts
@@ -1,14 +1,14 @@
import { Command } from 'commander';
import { confirm } from '@inquirer/prompts';
-import chalk from 'chalk';
import { logout as logoutApi } from '../api/auth.js';
import { loadCredentials, clearCredentials } from '../config.js';
-import { success, warn, spinner, wrapAction } from '../utils.js';
+import { success, warn, spinner, wrapAction, sanitizeTerminal } from '../utils.js';
export const logoutCommand = new Command('logout')
.description('Logout from your Minara account')
.option('-y, --yes', 'Skip confirmation')
- .action(wrapAction(async (opts: { yes?: boolean }) => {
+ .option('--local', 'Only remove local credentials, even if the server session cannot be revoked')
+ .action(wrapAction(async (opts: { yes?: boolean; local?: boolean }) => {
const creds = loadCredentials();
if (!creds?.accessToken) {
warn('You are not logged in.');
@@ -24,13 +24,33 @@ export const logoutCommand = new Command('logout')
}
const spin = spinner('Logging out…');
+ let failure: string | undefined;
try {
- await logoutApi(creds.accessToken);
- } catch {
- // Server-side logout failure is non-critical — we still clear local creds
- console.log(chalk.dim('Note: Server-side session invalidation skipped.'));
+ const res = await logoutApi(creds.accessToken);
+ if (!res.success && res.error?.code !== 401) {
+ // 401 means the session is already invalid on the server: nothing to revoke
+ failure = sanitizeTerminal(res.error?.message ?? 'unknown error');
+ }
+ } catch (err) {
+ failure = sanitizeTerminal(err instanceof Error ? err.message : String(err));
}
+ spin.stop();
+
+ if (failure && !opts.local) {
+ // Keep the token so the user can retry: once it is deleted locally the
+ // server session can no longer be revoked from this machine.
+ throw new Error(
+ `Could not revoke your session on the server (${failure}). `
+ + 'Your local credentials were kept so you can retry `minara logout`. '
+ + 'To remove them anyway, run `minara logout --local`.',
+ );
+ }
+
clearCredentials();
- spin.succeed('Logged out');
- success('Local credentials cleared.');
+ if (failure) {
+ warn(`The server session could not be revoked (${failure}); it stays valid until it expires.`);
+ success('Local credentials cleared.');
+ } else {
+ success('Logged out: server session revoked and local credentials cleared.');
+ }
}));
diff --git a/src/commands/perps.ts b/src/commands/perps.ts
index 1627ed7..cc3134f 100644
--- a/src/commands/perps.ts
+++ b/src/commands/perps.ts
@@ -7,6 +7,10 @@ import { success, info, warn, spinner, assertApiOk, formatOrderSide, wrapAction,
import { requireTouchId } from '../touchid.js';
import { printTxResult, printTable, printKV, POSITION_COLUMNS, FILL_COLUMNS } from '../formatters.js';
import type { PerpsOrder, PerpSubAccount } from '../types.js';
+import {
+ HL_MIN_ORDER_USD, canonicalDecimal, extractOrderStatuses, formatHlPrice, formatHlSize,
+ hlPriceError, hlSizeError, isPositiveDecimal, marketOrderPrice, type HlOrderStatus,
+} from '../hl-format.js';
// ─── shared helpers ──────────────────────────────────────────────────────
@@ -23,14 +27,69 @@ function getSubAccountId(w: PerpSubAccount): string {
}
function getSubAccountLabel(w: PerpSubAccount): string {
- const name = w.name ?? 'Unnamed';
+ const name = sanitizeTerminal(w.name ?? 'Unnamed');
const def = w.isDefault ? chalk.dim(' (default)') : '';
return `${name}${def}`;
}
/** Plain-text wallet label (no colors) for transaction confirmation rows. */
function walletText(w: PerpSubAccount): string {
- return `${w.name ?? 'Unnamed'}${w.isDefault ? ' (default)' : ''}`;
+ return `${sanitizeTerminal(w.name ?? 'Unnamed')}${w.isDefault ? ' (default)' : ''}`;
+}
+
+/** "Stop Market · reduce-only · trigger $95,000" for open orders that carry these details. */
+function describeOpenOrder(o: Record): string {
+ const parts: string[] = [];
+ if (o.orderType) parts.push(sanitizeTerminal(o.orderType));
+ if (o.reduceOnly === true) parts.push('reduce-only');
+ if (o.isTrigger === true && Number(o.triggerPx) > 0) parts.push(`trigger $${Number(o.triggerPx).toLocaleString()}`);
+ if (o.isPositionTpsl === true) parts.push('position TP/SL');
+ return parts.join(' · ');
+}
+
+/** Reduce-only and TP/SL trigger orders protect an open position. */
+function protectsPosition(o: Record): boolean {
+ return o.reduceOnly === true || o.isTrigger === true || o.isPositionTpsl === true;
+}
+
+/** First rejection message Hyperliquid returned for an order, if any. */
+function orderRejection(data: unknown): string | undefined {
+ const rejected = extractOrderStatuses(data)?.find((s) => s.kind === 'error');
+ return rejected?.kind === 'error' ? sanitizeTerminal(rejected.message) : undefined;
+}
+
+/**
+ * Report what Hyperliquid did with a single order. Hyperliquid answers "ok"
+ * even when an order is rejected (no liquidity for an IOC, tick size, $10
+ * minimum…), so check the per-order status and fail loudly on a rejection
+ * instead of claiming the order went through.
+ */
+function reportOrderOutcome(
+ data: unknown,
+ ctx: { symbol: string; size: string; wallet: string; ioc: boolean; close?: boolean },
+): void {
+ const rejection = orderRejection(data);
+ if (rejection) {
+ throw new Error(`Hyperliquid rejected the ${ctx.close ? 'close ' : ''}order: ${rejection}`);
+ }
+ const statuses = extractOrderStatuses(data) ?? [];
+ const fill = statuses.find((s): s is Extract => s.kind === 'filled');
+ if (fill) {
+ success(`${ctx.close ? 'Closed' : 'Filled'} ${fill.totalSz} ${ctx.symbol} @ $${fill.avgPx} on ${ctx.wallet}`);
+ if (Number(fill.totalSz) < Number(ctx.size)) {
+ warn(`Only ${fill.totalSz} of ${ctx.size} filled; the rest was cancelled (immediate-or-cancel).`
+ + (ctx.close ? ' Part of the position is still open.' : ''));
+ }
+ return;
+ }
+ if (statuses.some((s) => s.kind === 'resting')) {
+ success(`Order placed on ${ctx.wallet} (resting on the order book).`);
+ return;
+ }
+ success(ctx.close
+ ? `Close order submitted: ${ctx.symbol} ${ctx.size} on ${ctx.wallet}`
+ : `Order submitted on ${ctx.wallet}!`);
+ if (ctx.ioc) info('The response had no fill details. Confirm with: minara perps positions');
}
/** Help text for `-y` on commands whose transaction confirmation cannot be skipped. */
@@ -308,8 +367,8 @@ function getAllStrategiesForWallet(states: AutopilotState[], walletId: string, i
}
function strategyDisplayName(s: AutopilotState): string {
- if (s.name) return s.name;
- if (s.strategyId) return s.strategyId.length > 12 ? s.strategyId.slice(0, 12) + '…' : s.strategyId;
+ if (s.name) return sanitizeTerminal(s.name);
+ if (s.strategyId) return sanitizeTerminal(s.strategyId.length > 12 ? s.strategyId.slice(0, 12) + '…' : s.strategyId);
return 'Unnamed';
}
@@ -580,7 +639,7 @@ const orderCmd = new Command('order')
}
for (const [flag, value] of [['--price', opts.price], ['--size', opts.size]] as const) {
- if (value !== undefined && !(Number(value) > 0)) {
+ if (value !== undefined && !isPositiveDecimal(value)) {
throw new Error(`${flag} must be a positive number`);
}
}
@@ -611,7 +670,9 @@ const orderCmd = new Command('order')
info('Building a Hyperliquid perps order…');
const dataSpin = spinner('Fetching market data…');
- const address = await perpsApi.getPerpsAddress(creds.accessToken);
+ // Leverage is per wallet: read it from the wallet this order goes to. A
+ // sub-wallet must never show the default wallet's leverage.
+ const address = walletId ? (wallet.address ?? null) : await perpsApi.getPerpsAddress(creds.accessToken);
const [assets, leverages] = await Promise.all([
perpsApi.getAssetMeta(),
address ? perpsApi.getUserLeverage(address) : Promise.resolve([]),
@@ -668,9 +729,11 @@ const orderCmd = new Command('order')
const currentLev = leverageMap.get(asset.toUpperCase());
if (currentLev) {
- info(`Current leverage: ${currentLev.value}x (${currentLev.type})`);
+ info(`Current leverage on ${getSubAccountLabel(wallet)}: ${currentLev.value}x (${currentLev.type})`);
+ } else if (!address) {
+ warn(`Could not read the leverage of ${getSubAccountLabel(wallet)}.`);
} else {
- info(`No leverage set for ${asset} — use 'minara perps leverage' to configure`);
+ info(`No leverage set for ${asset} on ${getSubAccountLabel(wallet)} — use 'minara perps leverage' to configure`);
}
// ── Order Type ───────────────────────────────────────────────────────
@@ -718,8 +781,7 @@ const orderCmd = new Command('order')
marketPx = Number(opts.price);
info(`Market order at ~$${marketPx}`);
} else if (marketPx && marketPx > 0) {
- const slippagePx = isBuy ? marketPx * 1.01 : marketPx * 0.99;
- limitPx = slippagePx.toPrecision(5);
+ limitPx = marketOrderPrice(marketPx, isBuy, assetMeta?.szDecimals ?? 0);
info(`Market order at ~$${marketPx}`);
} else if (nonInteractive) {
console.error(chalk.red('✖'), `Could not fetch current price for ${asset}. Use --price to specify.`);
@@ -779,6 +841,23 @@ const orderCmd = new Command('order')
});
}
+ // ── Hyperliquid tick / lot / minimum value ───────────────────────────
+ // Without asset metadata only the universal limits apply (≤ 6 decimals).
+ const priceErr = hlPriceError(limitPx, assetMeta?.szDecimals ?? 0);
+ if (priceErr) {
+ const hint = isPositiveDecimal(limitPx)
+ ? ` (nearest valid: ${formatHlPrice(Number(limitPx), assetMeta?.szDecimals ?? 0)})` : '';
+ throw new Error(`Price ${limitPx} ${priceErr} for ${asset} on Hyperliquid${hint}`);
+ }
+ const sizeErr = hlSizeError(sz, assetMeta?.szDecimals ?? Number.POSITIVE_INFINITY);
+ if (sizeErr) throw new Error(`Size ${sz} ${sizeErr} for ${asset} on Hyperliquid`);
+ limitPx = canonicalDecimal(limitPx);
+ sz = canonicalDecimal(sz);
+ const notional = Number(sz) * (marketPx ?? Number(limitPx));
+ if (!reduceOnly && notional < HL_MIN_ORDER_USD) {
+ throw new Error(`Order value ~${fmt(notional)} is below Hyperliquid's $${HL_MIN_ORDER_USD} minimum. Increase --size.`);
+ }
+
const order: PerpsOrder = {
a: asset,
b: isBuy,
@@ -794,22 +873,28 @@ const orderCmd = new Command('order')
const priceLabel = orderType === 'market' ? `Market (~$${marketPx ?? limitPx})` : `$${limitPx}`;
- const levLabel = currentLev ? `${currentLev.value}x (${currentLev.type})` : '—';
+ const levLabel = currentLev ? `${currentLev.value}x (${currentLev.type})` : (address ? '—' : 'unknown');
console.log('');
console.log(chalk.bold('Order Preview:'));
+ console.log(` Wallet : ${getSubAccountLabel(wallet)}`);
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 (IOC)' : 'Limit (GTC)'}`);
console.log(` Price : ${chalk.yellow(priceLabel)}`);
console.log(` Size : ${chalk.bold(order.s)}`);
+ console.log(` Notional : ~${fmt(notional)}`);
console.log(` Reduce Only : ${order.r ? chalk.yellow('Yes') : 'No'}`);
console.log(` Grouping : ${grouping}`);
console.log('');
if (!opts.yes) {
- await requireTransactionConfirmation(`Perps ${order.b ? 'LONG' : 'SHORT'} ${order.a} · size ${order.s} @ ${priceLabel}`);
+ await requireTransactionConfirmation(`Perps ${order.b ? 'LONG' : 'SHORT'} ${order.a} · size ${order.s} @ ${priceLabel}`, undefined, {
+ side: order.b ? 'buy' : 'sell',
+ amount: `${order.s} ${order.a} (~${fmt(notional)})`,
+ extra: [['Wallet', walletText(wallet)], ['Leverage', levLabel]],
+ });
}
await requireTouchId();
@@ -817,7 +902,9 @@ const orderCmd = new Command('order')
const res = await perpsApi.placeOrders(creds.accessToken, { orders: [order], grouping, subAccountId: walletId });
spin.stop();
assertApiOk(res, 'Order placement failed');
- success(`Order submitted on ${getSubAccountLabel(wallet)}!`);
+ reportOrderOutcome(res.data, {
+ symbol: order.a, size: order.s, wallet: getSubAccountLabel(wallet), ioc: orderType === 'market',
+ });
printTxResult(res.data);
}));
@@ -862,21 +949,39 @@ const cancelCmd = new Command('cancel')
choices: openOrders.map((o) => {
const side = o.side === 'B' ? chalk.green('BUY') : chalk.red('SELL');
const px = `$${Number(o.limitPx ?? 0).toLocaleString()}`;
+ const kind = describeOpenOrder(o);
return {
- name: `${chalk.bold(String(o.coin ?? '').padEnd(6))} ${side} ${o.sz} @ ${chalk.yellow(px)} ${chalk.dim(`oid:${o.oid}`)}`,
+ name: `${chalk.bold(sanitizeTerminal(o.coin ?? '').padEnd(6))} ${side} ${sanitizeTerminal(o.sz)} @ ${chalk.yellow(px)}`
+ + `${kind ? ` ${chalk.cyan(kind)}` : ''} ${chalk.dim(`oid:${sanitizeTerminal(o.oid)}`)}`,
value: o,
};
}),
});
+ // Cancelling can leave a position without its stop-loss / take-profit,
+ // so it goes through the same confirmation and Touch ID as placing orders.
+ const sideLabel = selected.side === 'B' ? 'BUY' : 'SELL';
+ const coin = sanitizeTerminal(selected.coin ?? '');
+ const kind = describeOpenOrder(selected);
+ if (protectsPosition(selected)) {
+ warn(`This ${kind || 'order'} protects an open ${coin} position. Cancelling it leaves the position without it.`);
+ }
if (!opts.yes) {
- const sideLabel = selected.side === 'B' ? 'BUY' : 'SELL';
- const ok = await confirm({
- message: `Cancel ${sideLabel} ${selected.coin} ${selected.sz} @ $${Number(selected.limitPx ?? 0).toLocaleString()}?`,
- default: false,
- });
- if (!ok) return;
+ await requireTransactionConfirmation(
+ `Cancel ${sideLabel} ${coin} ${sanitizeTerminal(selected.sz)} @ $${Number(selected.limitPx ?? 0).toLocaleString()}`,
+ undefined,
+ {
+ side: `cancel ${sideLabel.toLowerCase()}`,
+ amount: `${sanitizeTerminal(selected.sz)} ${coin}`,
+ extra: [
+ ['Wallet', walletText(wallet)],
+ ...(kind ? [['Order type', kind] as [string, string]] : []),
+ ['Order ID', sanitizeTerminal(selected.oid)],
+ ],
+ },
+ );
}
+ await requireTouchId();
const cancelSpin = spinner('Cancelling…');
const res = await perpsApi.cancelOrders(creds.accessToken, {
@@ -965,26 +1070,29 @@ const closeCmd = new Command('close')
const assetMeta = assets.find((a) => a.name.toUpperCase() === symbol.toUpperCase());
const marketPx = assetMeta?.markPx;
- if (!marketPx || marketPx <= 0) {
+ if (!assetMeta || !marketPx || marketPx <= 0) {
results.push({ symbol, side, success: false, error: 'Could not fetch price' });
continue;
}
- const slippagePx = isBuy ? marketPx * 1.01 : marketPx * 0.99;
- const limitPx = slippagePx.toPrecision(5);
-
- const order: PerpsOrder = {
- a: symbol,
- b: isBuy,
- p: limitPx,
- s: sz,
- r: true,
- t: { limit: { tif: 'Ioc' } },
- };
-
try {
+ const order: PerpsOrder = {
+ a: symbol,
+ b: isBuy,
+ p: marketOrderPrice(marketPx, isBuy, assetMeta.szDecimals),
+ s: formatHlSize(Number(sz), assetMeta.szDecimals),
+ r: true,
+ t: { limit: { tif: 'Ioc' } },
+ };
const orderRes = await perpsApi.placeOrders(creds.accessToken, { orders: [order], grouping: 'na', subAccountId: walletId });
- if (orderRes.success) {
+ const rejection = orderRes.success ? orderRejection(orderRes.data) : undefined;
+ const fill = extractOrderStatuses(orderRes.data)
+ ?.find((st): st is Extract => st.kind === 'filled');
+ if (rejection) {
+ results.push({ symbol, side, success: false, error: rejection });
+ } else if (orderRes.success && fill && Number(fill.totalSz) < Number(order.s)) {
+ results.push({ symbol, side, success: false, error: `only ${fill.totalSz} of ${order.s} filled; part of the position is still open` });
+ } else if (orderRes.success) {
results.push({ symbol, side, success: true });
} else {
const errMsg = orderRes.error ? `${orderRes.error.code}: ${orderRes.error.message}` : 'Unknown error';
@@ -1011,8 +1119,9 @@ const closeCmd = new Command('close')
if (failed.length > 0) {
warn(`Failed to close ${failed.length} position(s):`);
failed.forEach((r) => {
- console.log(` ✗ ${r.symbol} ${r.side.toUpperCase()}: ${r.error}`);
+ console.log(` ✗ ${sanitizeTerminal(r.symbol)} ${r.side.toUpperCase()}: ${sanitizeTerminal(r.error)}`);
});
+ process.exitCode = 1;
}
};
@@ -1076,19 +1185,16 @@ const closeCmd = new Command('close')
const assetMeta = assets.find((a) => a.name.toUpperCase() === symbol.toUpperCase());
const marketPx = assetMeta?.markPx;
- if (!marketPx || marketPx <= 0) {
+ if (!assetMeta || !marketPx || marketPx <= 0) {
warn(`Could not fetch current price for ${symbol}. Cannot place market close order.`);
return;
}
- const slippagePx = isBuy ? marketPx * 1.01 : marketPx * 0.99;
- const limitPx = slippagePx.toPrecision(5);
-
const order: PerpsOrder = {
a: symbol,
b: isBuy,
- p: limitPx,
- s: sz,
+ p: marketOrderPrice(marketPx, isBuy, assetMeta.szDecimals),
+ s: formatHlSize(Number(sz), assetMeta.szDecimals),
r: true,
t: { limit: { tif: 'Ioc' } },
};
@@ -1110,7 +1216,9 @@ const closeCmd = new Command('close')
const orderRes = await perpsApi.placeOrders(creds.accessToken, { orders: [order], grouping: 'na', subAccountId: walletId });
orderSpin.stop();
assertApiOk(orderRes, 'Close position failed');
- success(`Position closed — ${sideLabel} ${symbol} ${sz}`);
+ reportOrderOutcome(orderRes.data, {
+ symbol, size: order.s, wallet: getSubAccountLabel(wallet), ioc: true, close: true,
+ });
printTxResult(orderRes.data);
}));
@@ -1969,7 +2077,7 @@ const walletsCmd = new Command('wallets')
}
const defLabel = w.isDefault ? chalk.cyan(' (default)') : '';
- console.log(` ${chalk.bold(w.name ?? 'Unnamed')}${defLabel} ${apLabel}`);
+ console.log(` ${chalk.bold(sanitizeTerminal(w.name ?? 'Unnamed'))}${defLabel} ${apLabel}`);
if (w.address) {
console.log(` Address : ${chalk.yellow(w.address)}`);
}
@@ -2377,13 +2485,13 @@ const askCmd = new Command('ask')
}
const isBuy = side === 'buy';
+ const szDecimals = symbolMeta?.szDecimals ?? 4;
// Slippage bound from the live mark price (not the AI's entry price)
- const slippagePx = isBuy ? markPx * 1.01 : markPx * 0.99;
const order: PerpsOrder = {
a: symbol,
b: isBuy,
- p: slippagePx.toPrecision(5),
- s: String(size),
+ p: marketOrderPrice(markPx, isBuy, szDecimals),
+ s: formatHlSize(size, szDecimals),
r: false,
t: { limit: { tif: 'Ioc' } },
};
@@ -2406,7 +2514,9 @@ const askCmd = new Command('ask')
const orderRes = await perpsApi.placeOrders(creds.accessToken, { orders: [order], grouping: 'na', subAccountId: orderWalletId });
orderSpin.stop();
assertApiOk(orderRes, 'Order placement failed');
- success(`Order submitted on ${getSubAccountLabel(orderWallet)}!`);
+ reportOrderOutcome(orderRes.data, {
+ symbol, size: order.s, wallet: getSubAccountLabel(orderWallet), ioc: true,
+ });
printTxResult(orderRes.data);
}));
@@ -2448,6 +2558,9 @@ export function buildQuickOrderPlan(
if (!(size > 0)) {
return { error: 'Resulting position size is too small for this asset.' };
}
+ if (size * markPx < HL_MIN_ORDER_USD) {
+ return { error: `Order value ~$${(size * markPx).toFixed(2)} is below Hyperliquid's $${HL_MIN_ORDER_USD} minimum — quick order disabled.` };
+ }
return { markPx, size, capped };
}
diff --git a/src/commands/premium.ts b/src/commands/premium.ts
index 295685b..003560d 100644
--- a/src/commands/premium.ts
+++ b/src/commands/premium.ts
@@ -5,7 +5,7 @@ import * as paymentApi from '../api/payment.js';
import { getCurrentUser } from '../api/auth.js';
import { requireAuth } from '../config.js';
import { success, info, warn, spinner, assertApiOk, wrapAction } from '../utils.js';
-import { openBrowser } from '../utils.js';
+import { openBrowser, sanitizeTerminal } from '../utils.js';
import { printKV, printTable, isRawJson } from '../formatters.js';
import type { PaymentPlan } from '../types.js';
@@ -234,7 +234,7 @@ const subscribeCmd = new Command('subscribe')
const selectedPlanId = await select({
message: 'Select a plan:',
choices: activePlans.map((p) => ({
- name: `${p.name} (${p.interval === 'month' ? 'Monthly' : 'Yearly'}) — ${formatPrice(p)} [${formatCredits(p.rules)} credits, ${p.rules.limitWorkflows ?? 0} workflows]`,
+ name: `${sanitizeTerminal(p.name)} (${p.interval === 'month' ? 'Monthly' : 'Yearly'}) — ${formatPrice(p)} [${formatCredits(p.rules)} credits, ${p.rules.limitWorkflows ?? 0} workflows]`,
value: p._id,
})),
});
@@ -254,7 +254,7 @@ const subscribeCmd = new Command('subscribe')
const priceStr = `$${selectedPlan.price}/${selectedPlan.interval === 'month' ? 'mo' : 'yr'}`;
console.log('');
console.log(chalk.bold('Order Summary:'));
- console.log(` Plan : ${chalk.bold(selectedPlan.name)} (${selectedPlan.interval === 'month' ? 'Monthly' : 'Yearly'})`);
+ console.log(` Plan : ${chalk.bold(sanitizeTerminal(selectedPlan.name))} (${selectedPlan.interval === 'month' ? 'Monthly' : 'Yearly'})`);
console.log(` Price : ${chalk.bold(priceStr)}`);
console.log(` Payment : ${payMethod === 'stripe' ? 'Credit Card (Stripe)' : 'Crypto (USDC)'}`);
console.log('');
@@ -291,7 +291,7 @@ async function handleStripeCheckout(token: string, planId: string): Promise limits.maxSlippagePct) {
+ return `quoted slippage tolerance ${slippagePct}% is above the ${limits.maxSlippagePct}% limit (--max-slippage)`;
+ }
+ const impact = Number(item.priceImpact);
+ // -1 means "negligible / not computed"
+ if (item.priceImpact !== null && item.priceImpact !== undefined && Number.isFinite(impact) && impact !== -1
+ && Math.abs(impact) > limits.maxPriceImpactPct) {
+ return `quoted price impact ${impact}% is above the ${limits.maxPriceImpactPct}% limit (--max-price-impact)`;
+ }
+ return null;
+}
+
+function parsePercentOption(value: string | undefined, flag: string, fallback: number): number {
+ if (value === undefined) return fallback;
+ const n = Number(value);
+ if (!/^\d+(\.\d+)?$/.test(value.trim()) || !(n > 0) || n > 100) {
+ throw new Error(`${flag} must be a percentage between 0 and 100`);
+ }
+ return n;
+}
+
export const swapCommand = new Command('swap')
.description('Swap tokens (cross-chain spot trading)')
.option('-s, --side ', 'buy or sell')
@@ -17,8 +55,14 @@ export const swapCommand = new Command('swap')
.option('-c, --chain ', 'Blockchain (ethereum, base, solana, etc.)')
.option('-y, --yes', 'Skip confirmation')
.option('--dry-run', 'Simulate without executing')
+ .option('--max-slippage ', `Refuse quotes with a slippage tolerance above this (default ${DEFAULT_MAX_SLIPPAGE_PCT})`)
+ .option('--max-price-impact ', `Refuse quotes with a price impact above this (default ${DEFAULT_MAX_PRICE_IMPACT_PCT})`)
.action(wrapAction(async (opts) => {
const creds = requireAuth();
+ const limits = {
+ maxSlippagePct: parsePercentOption(opts.maxSlippage, '--max-slippage', DEFAULT_MAX_SLIPPAGE_PCT),
+ maxPriceImpactPct: parsePercentOption(opts.maxPriceImpact, '--max-price-impact', DEFAULT_MAX_PRICE_IMPACT_PCT),
+ };
// ── 0. Validate CLI options early ────────────────────────────────────
if (opts.amount) {
@@ -126,27 +170,38 @@ export const swapCommand = new Command('swap')
return;
}
- // ── 6. Quote preview ─────────────────────────────────────────────────
- // Show expected output, fees, slippage and price impact before the user
- // approves, instead of only echoing their own input back.
- if (!opts.yes) {
- const quoteSpin = spinner('Fetching quote…');
- let quoteShown = false;
- try {
- const quoteRes = await swapsSimulate(creds.accessToken, [{
- chain, side, tokenAddress: tokenInfo.address, buyUsdAmountOrSellTokenAmount: amount,
- }]);
- quoteSpin.stop();
- if (quoteRes?.success && Array.isArray(quoteRes.data) && quoteRes.data.length > 0) {
- for (const item of quoteRes.data) printSwapSimulation(item);
- quoteShown = true;
+ // ── 6. Quote preview and limits ──────────────────────────────────────
+ // Always fetched, also with -y: show expected output, fees, slippage and
+ // price impact, and refuse quotes beyond the slippage / price-impact
+ // limits. (With -y --json the quote is not printed, so stdout stays a
+ // single JSON result, but the limits still apply.)
+ const quoteSpin = spinner('Fetching quote…');
+ let quote: CrossChainSwapsSimulateItem[] | undefined;
+ try {
+ const quoteRes = await swapsSimulate(creds.accessToken, [{
+ chain, side, tokenAddress: tokenInfo.address, buyUsdAmountOrSellTokenAmount: amount,
+ }]);
+ if (quoteRes?.success && Array.isArray(quoteRes.data) && quoteRes.data.length > 0) quote = quoteRes.data;
+ } catch {
+ // handled below
+ }
+ quoteSpin.stop();
+
+ if (quote) {
+ if (!(opts.yes && isRawJson())) for (const item of quote) printSwapSimulation(item);
+ const problem = quote.map((item) => quoteLimitError(item, limits)).find((e) => e !== null);
+ if (problem) {
+ if (problem.startsWith('the quote failed') && !opts.yes) {
+ warn(`Not recommended: ${problem}.`);
+ } else {
+ throw new Error(`Swap not sent: ${problem}.`);
}
- } catch {
- quoteSpin.stop();
- }
- if (!quoteShown) {
- warn('Could not fetch a quote — expected output, fees and slippage are unknown.');
}
+ } else if (opts.yes) {
+ // Nobody reviews an unattended swap: never send one blind
+ throw new Error('Swap not sent: could not fetch a quote. Run without -y to review and confirm it manually.');
+ } else {
+ warn('Could not fetch a quote — expected output, fees and slippage are unknown.');
}
// ── 7. Confirm & Touch ID ──────────────────────────────────────────
diff --git a/src/commands/transfer.ts b/src/commands/transfer.ts
index ddeb613..175511c 100644
--- a/src/commands/transfer.ts
+++ b/src/commands/transfer.ts
@@ -3,7 +3,7 @@ import { input } from '@inquirer/prompts';
import chalk from 'chalk';
import { transfer } from '../api/crosschain.js';
import { requireAuth } from '../config.js';
-import { success, spinner, assertApiOk, selectChain, wrapAction, requireTransactionConfirmation, lookupToken, validateAddress, parseChainOption, assertTokenOnChain } from '../utils.js';
+import { success, spinner, assertApiOk, selectChain, wrapAction, requireTransactionConfirmation, lookupToken, validateAddress, parseChainOption, assertTokenOnChain, recipientAddressWarning, warn } from '../utils.js';
import type { Chain } from '../types.js';
import { requireTouchId } from '../touchid.js';
import { printTxResult } from '../formatters.js';
@@ -62,6 +62,8 @@ export const transferCommand = new Command('transfer')
message: 'Recipient address:',
validate: (v) => validateAddress(v, chain),
})).trim();
+ const recipientWarning = recipientAddressWarning(recipient, chain);
+ if (recipientWarning) warn(recipientWarning);
// ── 5. Confirm & Touch ID ──────────────────────────────────────────
if (!opts.yes) {
diff --git a/src/commands/withdraw.ts b/src/commands/withdraw.ts
index 4c82213..8ed8821 100644
--- a/src/commands/withdraw.ts
+++ b/src/commands/withdraw.ts
@@ -3,7 +3,7 @@ import { input } from '@inquirer/prompts';
import chalk from 'chalk';
import { transfer, getAssets } from '../api/crosschain.js';
import { requireAuth } from '../config.js';
-import { success, spinner, assertApiOk, selectChain, wrapAction, requireTransactionConfirmation, lookupToken, validateAddress, parseChainOption, assertTokenOnChain, sanitizeTerminal } from '../utils.js';
+import { success, spinner, assertApiOk, selectChain, wrapAction, requireTransactionConfirmation, lookupToken, validateAddress, parseChainOption, assertTokenOnChain, sanitizeTerminal, recipientAddressWarning, warn } from '../utils.js';
import type { Chain } from '../types.js';
import { requireTouchId } from '../touchid.js';
import { printTxResult } from '../formatters.js';
@@ -88,6 +88,8 @@ export const withdrawCommand = new Command('withdraw')
message: 'Destination address (your external wallet):',
validate: (v) => validateAddress(v, chain),
})).trim();
+ const recipientWarning = recipientAddressWarning(recipient, chain);
+ if (recipientWarning) warn(recipientWarning);
// ── 6. Confirm & Touch ID ──────────────────────────────────────────
if (!opts.yes) {
diff --git a/src/config.ts b/src/config.ts
index 2022b70..3953f0f 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -1,4 +1,4 @@
-import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync, unlinkSync } from 'node:fs';
+import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync, unlinkSync, renameSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import type { Credentials } from './types.js';
@@ -27,11 +27,22 @@ function ensureDir(): void {
}
/**
- * Write a private file. `mode` in writeFileSync only applies when the file is
- * created, so permissions are re-applied explicitly for pre-existing files.
+ * Write a private file atomically: write a temp file next to it, then rename
+ * it over the target, so an interrupted write (crash, full disk, Ctrl-C)
+ * leaves either the old file or the new one, never a truncated file.
+ * `mode` in writeFileSync only applies when the file is created, so
+ * permissions are re-applied explicitly.
*/
function writePrivateFile(path: string, content: string): void {
- writeFileSync(path, content, { encoding: 'utf-8', mode: 0o600 });
+ const tmp = `${path}.${process.pid}.tmp`;
+ try {
+ writeFileSync(tmp, content, { encoding: 'utf-8', mode: 0o600, flush: true });
+ tightenMode(tmp, 0o600);
+ renameSync(tmp, path);
+ } catch (err) {
+ try { unlinkSync(tmp); } catch { /* already gone */ }
+ throw err;
+ }
tightenMode(path, 0o600);
}
@@ -76,6 +87,12 @@ export interface AppConfig {
baseUrl: string;
touchId?: boolean;
confirmBeforeTransaction?: boolean;
+ /**
+ * Set (never saved) when config.json exists but could not be read or
+ * parsed. Protections it may have enabled are unknown, so fund operations
+ * refuse to run until the file is fixed or reset (fail closed).
+ */
+ loadError?: string;
}
export const DEFAULT_BASE_URL = 'https://api.minara.ai';
@@ -87,18 +104,36 @@ const DEFAULT_CONFIG: AppConfig = {
export function loadConfig(): AppConfig {
if (!existsSync(CONFIG_FILE)) return { ...DEFAULT_CONFIG };
+ let parsed: unknown;
try {
- const raw = readFileSync(CONFIG_FILE, 'utf-8');
- return { ...DEFAULT_CONFIG, ...JSON.parse(raw) };
- } catch {
- return { ...DEFAULT_CONFIG };
+ parsed = JSON.parse(readFileSync(CONFIG_FILE, 'utf-8'));
+ } catch (err) {
+ const reason = err instanceof Error ? err.message : String(err);
+ return { ...DEFAULT_CONFIG, loadError: `could not read ${CONFIG_FILE}: ${reason}` };
+ }
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
+ return { ...DEFAULT_CONFIG, loadError: `${CONFIG_FILE} does not contain a JSON object` };
}
+ const { loadError: _ignored, ...stored } = parsed as Partial;
+ return { ...DEFAULT_CONFIG, ...stored };
+}
+
+/**
+ * Message for fund operations when config.json is unreadable. Touch ID or
+ * transaction confirmation may have been enabled in the damaged file, so the
+ * CLI refuses rather than silently running without them.
+ */
+export function configLoadErrorMessage(loadError: string): string {
+ return `Your Minara config is damaged (${loadError}). `
+ + 'Fund operations are blocked because Touch ID / transaction confirmation settings in it cannot be read. '
+ + 'Fix the file, or run `minara config` to rewrite it.';
}
export function saveConfig(config: Partial): void {
ensureDir();
- const current = loadConfig();
- const merged = { ...current, ...config };
+ const { loadError: _ignored, ...current } = loadConfig();
+ const { loadError: _ignored2, ...update } = config;
+ const merged = { ...current, ...update };
writePrivateFile(CONFIG_FILE, JSON.stringify(merged, null, 2));
}
diff --git a/src/hl-format.ts b/src/hl-format.ts
new file mode 100644
index 0000000..f09268d
--- /dev/null
+++ b/src/hl-format.ts
@@ -0,0 +1,132 @@
+/**
+ * Hyperliquid perp order formatting and result parsing.
+ *
+ * Tick / lot rules (https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/tick-and-lot-size):
+ * - price: at most 5 significant figures and at most `6 - szDecimals`
+ * decimal places; integer prices are always valid
+ * - size: at most `szDecimals` decimal places
+ * - wire strings are plain decimals with no exponent and no trailing zeros
+ * (trailing zeros change the signed payload and the order is rejected)
+ * - new orders must be worth at least $10; a reduce-only order that closes
+ * the whole position is exempt
+ */
+
+export const HL_PERP_MAX_DECIMALS = 6;
+export const HL_MIN_ORDER_USD = 10;
+/** Price buffer for market (IOC) orders, same as the official SDKs. */
+export const MARKET_SLIPPAGE = 0.01;
+
+const DECIMAL_RE = /^\d+(?:\.\d+)?$/;
+
+/** A plain positive decimal ("0.5", "97000"): no sign, exponent, hex or spaces. */
+export function isPositiveDecimal(value: string): boolean {
+ return DECIMAL_RE.test(value.trim()) && Number(value) > 0;
+}
+
+function decimalsFor(szDecimals: number): number {
+ return Math.max(0, HL_PERP_MAX_DECIMALS - Math.max(0, Math.floor(szDecimals)));
+}
+
+/** Plain decimal string without leading or trailing zeros: "007.50" → "7.5". */
+export function canonicalDecimal(value: string): string {
+ let s = value.trim();
+ if (s.includes('.')) s = s.replace(/0+$/, '').replace(/\.$/, '');
+ s = s.replace(/^0+(?=\d)/, '');
+ return s;
+}
+
+/** Round a price to the nearest valid perp price and return its wire string. */
+export function formatHlPrice(px: number, szDecimals: number): string {
+ if (!Number.isFinite(px) || px <= 0) throw new Error(`Invalid price: ${px}`);
+ // toPrecision may use exponent notation (1.0201e+5); Number() parses it back
+ const sig5 = Number(px.toPrecision(5));
+ const out = canonicalDecimal(sig5.toFixed(decimalsFor(szDecimals)));
+ if (!(Number(out) > 0)) throw new Error(`Price ${px} is below the smallest tick for this asset`);
+ return out;
+}
+
+/** Worst acceptable price for a market (IOC) order, 1% through the mark price. */
+export function marketOrderPrice(markPx: number, isBuy: boolean, szDecimals: number): string {
+ return formatHlPrice(markPx * (isBuy ? 1 + MARKET_SLIPPAGE : 1 - MARKET_SLIPPAGE), szDecimals);
+}
+
+/** Size wire string, rounded to the asset's size decimals. */
+export function formatHlSize(sz: number, szDecimals: number): string {
+ if (!Number.isFinite(sz) || sz <= 0) throw new Error(`Invalid size: ${sz}`);
+ const out = canonicalDecimal(sz.toFixed(Math.max(0, Math.floor(szDecimals))));
+ if (!(Number(out) > 0)) throw new Error(`Size ${sz} is below the smallest lot for this asset`);
+ return out;
+}
+
+/** Why a user-entered price would be rejected by Hyperliquid, or null if it is valid. */
+export function hlPriceError(value: string, szDecimals: number): string | null {
+ const s = value.trim();
+ if (!isPositiveDecimal(s)) return 'must be a plain positive number';
+ const [intPart, frac = ''] = s.split('.');
+ const fracDigits = frac.replace(/0+$/, '');
+ if (fracDigits === '') return null; // integer prices are always valid
+ const maxDecimals = decimalsFor(szDecimals);
+ if (fracDigits.length > maxDecimals) return `has more than ${maxDecimals} decimal place(s)`;
+ const sigDigits = (intPart + fracDigits).replace(/^0+/, '');
+ if (sigDigits.length > 5) return 'has more than 5 significant figures';
+ return null;
+}
+
+/** Why a user-entered size would be rejected by Hyperliquid, or null if it is valid. */
+export function hlSizeError(value: string, szDecimals: number): string | null {
+ const s = value.trim();
+ if (!isPositiveDecimal(s)) return 'must be a plain positive number';
+ const fracDigits = (s.split('.')[1] ?? '').replace(/0+$/, '');
+ const max = Math.max(0, Math.floor(szDecimals));
+ if (fracDigits.length > max) return `has more than ${max} decimal place(s)`;
+ return null;
+}
+
+// ─── Order results ───────────────────────────────────────────────────────
+
+export type HlOrderStatus =
+ | { kind: 'filled'; totalSz: string; avgPx: string }
+ | { kind: 'resting'; oid?: number }
+ | { kind: 'error'; message: string }
+ | { kind: 'other'; value: string };
+
+function isPlainObject(v: unknown): v is Record {
+ return !!v && typeof v === 'object' && !Array.isArray(v);
+}
+
+function findStatuses(data: unknown, depth = 0): unknown[] | null {
+ if (!isPlainObject(data) || depth > 4) return null;
+ if (Array.isArray(data.statuses)) return data.statuses;
+ for (const v of Object.values(data)) {
+ const found = findStatuses(v, depth + 1);
+ if (found) return found;
+ }
+ return null;
+}
+
+/**
+ * Per-order statuses from a place-orders response. Hyperliquid answers
+ * `{status:'ok', response:{data:{statuses:[...]}}}` even when an order is
+ * rejected, so a successful HTTP response alone does not mean it executed.
+ * Returns null when the response carries no statuses.
+ */
+export function extractOrderStatuses(data: unknown): HlOrderStatus[] | null {
+ if (isPlainObject(data) && data.status === 'err' && typeof data.response === 'string') {
+ return [{ kind: 'error', message: data.response }];
+ }
+ const raw = findStatuses(data);
+ if (!raw) return null;
+ return raw.map((s): HlOrderStatus => {
+ if (isPlainObject(s)) {
+ if (typeof s.error === 'string') return { kind: 'error', message: s.error };
+ if (isPlainObject(s.filled)) {
+ return { kind: 'filled', totalSz: String(s.filled.totalSz ?? ''), avgPx: String(s.filled.avgPx ?? '') };
+ }
+ if (isPlainObject(s.resting)) {
+ return { kind: 'resting', oid: typeof s.resting.oid === 'number' ? s.resting.oid : undefined };
+ }
+ return { kind: 'other', value: JSON.stringify(s) };
+ }
+ return { kind: 'other', value: String(s) };
+ });
+}
diff --git a/src/sanitize.ts b/src/sanitize.ts
new file mode 100644
index 0000000..31d8f55
--- /dev/null
+++ b/src/sanitize.ts
@@ -0,0 +1,60 @@
+/**
+ * Terminal sanitization for untrusted text (server / on-chain / AI output).
+ *
+ * Kept dependency-free so the API client can sanitize every response at the
+ * boundary without pulling in prompt / spinner modules.
+ */
+
+// CSI (ESC [ … final byte), OSC (ESC ] … BEL | ESC \), and two-byte ESC sequences
+// eslint-disable-next-line no-control-regex
+const ANSI_SEQUENCE_RE = /\u001b\[[0-?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|\u001b[@-Z\\-_]/g;
+// Removed outright:
+// - C0 controls (except \t and \n), DEL and C1 controls
+// - bidi marks, overrides and isolates (ALM, LRM/RLM, LRE…RLO, LRI…PDI)
+// - invisible / zero-width characters that make two strings look identical:
+// soft hyphen, combining grapheme joiner, Hangul / Khmer fillers,
+// Mongolian variation selectors, ZWSP/ZWNJ/ZWJ, word joiner and invisible
+// operators, variation selectors, BOM, interlinear annotation, musical
+// format characters, and Unicode tag characters ("ASCII smuggling")
+// eslint-disable-next-line no-control-regex, no-misleading-character-class
+const CONTROL_CHAR_RE = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u00ad\u034f\u061c\u115f\u1160\u17b4\u17b5\u180b-\u180f\u200b-\u200f\u202a-\u202e\u2060-\u206f\u3164\ufe00-\ufe0f\ufeff\uffa0\ufff9-\ufffb\u{1d173}-\u{1d17a}\u{e0000}-\u{e007f}\u{e0100}-\u{e01ef}]/gu;
+// Line separator / paragraph separator / NEL behave like line breaks in some terminals
+const LINE_BREAK_RE = /\r\n?|[\u0085\u2028\u2029]/g;
+
+/**
+ * Strip terminal control sequences from untrusted text (token metadata, API
+ * messages, chat output) so it cannot recolor, move the cursor, rewrite
+ * earlier lines, set the clipboard (OSC 52) or visually reorder characters.
+ *
+ * - Single-line mode (default): tabs and line breaks become a space so a value
+ * cannot fake extra rows in a confirmation prompt.
+ * - Multiline mode: `\n` is kept (CRLF, lone CR, NEL and the Unicode line /
+ * paragraph separators are normalised to `\n`).
+ */
+export function sanitizeTerminal(value: unknown, opts: { multiline?: boolean } = {}): string {
+ let s = String(value ?? '');
+ s = s.replace(ANSI_SEQUENCE_RE, '');
+ s = s.replace(LINE_BREAK_RE, '\n');
+ if (!opts.multiline) s = s.replace(/[\t\n]+/g, ' ');
+ return s.replace(CONTROL_CHAR_RE, '');
+}
+
+/**
+ * Recursively apply {@link sanitizeTerminal} to every string inside a
+ * payload. Keys are always sanitized in single-line mode; values use
+ * `opts.multiline` (default: single-line, for table / key-value display).
+ * The API client uses multiline mode on every response so line breaks in
+ * long text (chat, analysis, descriptions) survive.
+ */
+export function sanitizeDeep(value: T, opts: { multiline?: boolean } = {}): T {
+ if (typeof value === 'string') return sanitizeTerminal(value, opts) as T;
+ if (Array.isArray(value)) return value.map((v) => sanitizeDeep(v, opts)) as T;
+ if (value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype) {
+ const out: Record = {};
+ for (const [k, v] of Object.entries(value as Record)) {
+ out[sanitizeTerminal(k)] = sanitizeDeep(v, opts);
+ }
+ return out as T;
+ }
+ return value;
+}
diff --git a/src/touchid.ts b/src/touchid.ts
index c93c370..afd0504 100644
--- a/src/touchid.ts
+++ b/src/touchid.ts
@@ -7,7 +7,7 @@ import { existsSync, writeFileSync, unlinkSync, chmodSync, readFileSync } from '
import { join } from 'node:path';
import { platform } from 'node:os';
import chalk from 'chalk';
-import { loadConfig, getMinaraDir } from './config.js';
+import { loadConfig, getMinaraDir, configLoadErrorMessage } from './config.js';
// Bump this when SWIFT_SOURCE changes to force recompilation
const TOUCHID_BINARY_VERSION = '1';
@@ -157,6 +157,11 @@ export function verifyTouchId(reason?: string): void {
*/
export async function requireTouchId(): Promise {
const config = loadConfig();
+ if (config.loadError) {
+ // Touch ID may be enabled in the damaged file: fail closed
+ console.error(chalk.red('✖'), configLoadErrorMessage(config.loadError));
+ process.exit(1);
+ }
if (!config.touchId) return; // Touch ID not enabled — no-op
if (platform() !== 'darwin') {
diff --git a/src/utils.ts b/src/utils.ts
index bbc08dc..ec1460f 100644
--- a/src/utils.ts
+++ b/src/utils.ts
@@ -4,8 +4,9 @@ import { execFile } from 'node:child_process';
import { platform } from 'node:os';
import { select, confirm } from '@inquirer/prompts';
import type { ApiResponse, Chain } from './types.js';
+import { sanitizeTerminal } from './sanitize.js';
import { SUPPORTED_CHAINS } from './types.js';
-import { loadConfig } from './config.js';
+import { loadConfig, configLoadErrorMessage } from './config.js';
// ─── Logging helpers ─────────────────────────────────────────────────────────
@@ -62,47 +63,9 @@ export function truncate(str: string, len: number): string {
return str.length > len ? str.slice(0, len - 1) + '…' : str;
}
-// ─── Terminal sanitization ───────────────────────────────────────────────────
+// ─── Terminal sanitization (see sanitize.ts) ─────────────────────────────────
-// CSI (ESC [ … final byte), OSC (ESC ] … BEL | ESC \), and two-byte ESC sequences
-// eslint-disable-next-line no-control-regex
-const ANSI_SEQUENCE_RE = /\u001b\[[0-?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|\u001b[@-Z\\-_]/g;
-// C0 controls (except \t and \n), DEL, C1 controls, and bidi override / isolate characters
-// eslint-disable-next-line no-control-regex
-const CONTROL_CHAR_RE = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;
-
-/**
- * Strip terminal control sequences from untrusted text (token metadata, API
- * messages, chat output) so it cannot recolor, move the cursor, rewrite
- * earlier lines, set the clipboard (OSC 52) or visually reorder characters.
- *
- * - Single-line mode (default): tabs and line breaks become a space so a value
- * cannot fake extra rows in a confirmation prompt.
- * - Multiline mode: `\n` is kept (CRLF / lone CR are normalised to `\n`).
- */
-export function sanitizeTerminal(value: unknown, opts: { multiline?: boolean } = {}): string {
- let s = String(value ?? '');
- s = s.replace(ANSI_SEQUENCE_RE, '');
- s = opts.multiline ? s.replace(/\r\n?/g, '\n') : s.replace(/[\t\n\r]+/g, ' ');
- return s.replace(CONTROL_CHAR_RE, '');
-}
-
-/**
- * Recursively apply {@link sanitizeTerminal} to every string (values and keys)
- * inside an API payload before it is rendered as a table or key-value list.
- */
-export function sanitizeDeep(value: T): T {
- if (typeof value === 'string') return sanitizeTerminal(value) as T;
- if (Array.isArray(value)) return value.map((v) => sanitizeDeep(v)) as T;
- if (value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype) {
- const out: Record = {};
- for (const [k, v] of Object.entries(value as Record)) {
- out[sanitizeTerminal(k)] = sanitizeDeep(v);
- }
- return out as T;
- }
- return value;
-}
+export { sanitizeTerminal, sanitizeDeep } from './sanitize.js';
// ─── API error handling ───────────────────────────────────────────────────────
@@ -462,7 +425,7 @@ export async function lookupToken(tokenInput: string, opts: LookupTokenOptions =
const chainName = displayChain(t.chain);
const name = t.name ? ` — ${t.name}` : '';
const tag = sameSymbol && i === 0 && firstChainUnique ? chalk.green(' (lowest gas)') : '';
- const addr = t.address ? chalk.yellow(t.address) : chalk.dim('(native token)');
+ const addr = t.address ? chalk.yellow(sanitizeTerminal(t.address)) : chalk.dim('(native token)');
const mc = chalk.dim(`MC ${formatCompactUsd(t.marketCap)}`);
return { name: `${sym}${name} ${chalk.cyan(`[${chainName}]`)}${tag} ${mc}\n ${addr}`, value: t };
}),
@@ -514,6 +477,10 @@ export async function requireTransactionConfirmation(
details?: TransactionDetails,
): Promise {
const config = loadConfig();
+ if (config.loadError) {
+ // Confirmation may be enabled in the damaged file: fail closed
+ throw new Error(configLoadErrorMessage(config.loadError));
+ }
if (config.confirmBeforeTransaction === false) {
warn('Transaction confirmation is disabled in config (`minara config` to re-enable).');
return;
@@ -565,6 +532,89 @@ export async function requireTransactionConfirmation(
const SOLANA_ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
const EVM_ADDR_RE = /^0x[0-9a-fA-F]{40}$/;
+const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
+
+/** Decode a base58 string to bytes, or `null` if it contains non-base58 characters. */
+export function base58Decode(value: string): Uint8Array | null {
+ const bytes: number[] = [];
+ for (const ch of value) {
+ let carry = BASE58_ALPHABET.indexOf(ch);
+ if (carry < 0) return null;
+ for (let i = 0; i < bytes.length; i++) {
+ carry += bytes[i] * 58;
+ bytes[i] = carry & 0xff;
+ carry >>= 8;
+ }
+ while (carry > 0) {
+ bytes.push(carry & 0xff);
+ carry >>= 8;
+ }
+ }
+ // Each leading '1' encodes a leading zero byte
+ for (let i = 0; i < value.length && value[i] === '1'; i++) bytes.push(0);
+ return Uint8Array.from(bytes.reverse());
+}
+
+/**
+ * A Solana address is the base58 encoding of a 32-byte public key. Checking
+ * the decoded length rejects strings that only look like base58 (wrong
+ * length, typos that change the length, pasted fragments). Solana addresses
+ * have no checksum, so some mistyped addresses still decode to 32 bytes: the
+ * full address is always shown in the confirmation for the user to check.
+ */
+export function isSolanaAddress(value: string): boolean {
+ if (!SOLANA_ADDR_RE.test(value)) return false;
+ return base58Decode(value)?.length === 32;
+}
+
+// ed25519: p = 2^255 - 19, d = -121665 / 121666 mod p
+const ED_P = (1n << 255n) - 19n;
+function modPow(base: bigint, exp: bigint, mod: bigint): bigint {
+ let result = 1n;
+ let b = ((base % mod) + mod) % mod;
+ let e = exp;
+ while (e > 0n) {
+ if (e & 1n) result = (result * b) % mod;
+ b = (b * b) % mod;
+ e >>= 1n;
+ }
+ return result;
+}
+const ED_D = ((-121665n * modPow(121666n, ED_P - 2n, ED_P)) % ED_P + ED_P) % ED_P;
+
+/**
+ * Whether 32 bytes decode to a point on the ed25519 curve, i.e. could be a
+ * wallet's public key. Program-derived addresses (multisig vaults, program
+ * accounts) are deliberately off the curve, so this is only a hint.
+ */
+export function isOnEd25519Curve(bytes: Uint8Array): boolean {
+ if (bytes.length !== 32) return false;
+ let y = 0n;
+ for (let i = 31; i >= 0; i--) y = (y << 8n) | BigInt(i === 31 ? bytes[i] & 0x7f : bytes[i]);
+ const sign = bytes[31] >> 7;
+ if (y >= ED_P) return false;
+ const y2 = (y * y) % ED_P;
+ const u = (y2 - 1n + ED_P) % ED_P;
+ const v = (ED_D * y2 + 1n) % ED_P;
+ const x2 = (u * modPow(v, ED_P - 2n, ED_P)) % ED_P;
+ if (x2 === 0n) return sign === 0;
+ // x^2 must be a quadratic residue (Euler's criterion)
+ return modPow(x2, (ED_P - 1n) / 2n, ED_P) === 1n;
+}
+
+/**
+ * Non-blocking warning for a recipient that passed {@link validateAddress}
+ * but looks unusual. Returns `undefined` when there is nothing to flag.
+ */
+export function recipientAddressWarning(address: string, chain?: string): string | undefined {
+ const c = chain?.toLowerCase();
+ if (c !== 'solana' && c !== 'sol' && c !== '101') return undefined;
+ const bytes = base58Decode(address.trim());
+ if (!bytes || bytes.length !== 32 || isOnEd25519Curve(bytes)) return undefined;
+ return 'This Solana address is not a wallet public key. It may be a program-derived address '
+ + '(e.g. a multisig vault) or a mistyped / truncated address. Check every character before confirming.';
+}
+
/**
* Validate a blockchain address based on the target chain.
* Returns `true` on success or an error message string on failure.
@@ -575,7 +625,7 @@ export function validateAddress(address: string, chain?: string): true | string
const c = chain?.toLowerCase();
if (c === 'solana' || c === 'sol' || c === '101') {
- if (!SOLANA_ADDR_RE.test(v)) return 'Invalid Solana address (expected base58, 32–44 chars)';
+ if (!isSolanaAddress(v)) return 'Invalid Solana address (expected a base58-encoded 32-byte public key)';
return true;
}
if (c && c !== 'solana') {
@@ -583,7 +633,7 @@ export function validateAddress(address: string, chain?: string): true | string
return true;
}
// Unknown chain — accept either format
- if (!SOLANA_ADDR_RE.test(v) && !EVM_ADDR_RE.test(v)) {
+ if (!isSolanaAddress(v) && !EVM_ADDR_RE.test(v)) {
return 'Invalid address format';
}
return true;
diff --git a/tests/api/auth.test.ts b/tests/api/auth.test.ts
index f7cdb0e..336b2df 100644
--- a/tests/api/auth.test.ts
+++ b/tests/api/auth.test.ts
@@ -79,10 +79,10 @@ describe('auth API', () => {
});
describe('logout', () => {
- it('should POST /auth/logout with auth token', async () => {
+ it('should POST /auth/logout with auth token and no re-login on 401', async () => {
await logout('my-token');
- expect(mockPost).toHaveBeenCalledWith('/auth/logout', { token: 'my-token' });
+ expect(mockPost).toHaveBeenCalledWith('/auth/logout', { token: 'my-token', noReauth: true });
});
});
diff --git a/tests/api/client-baseurl.test.ts b/tests/api/client-baseurl.test.ts
index 8b82185..216c188 100644
--- a/tests/api/client-baseurl.test.ts
+++ b/tests/api/client-baseurl.test.ts
@@ -32,13 +32,28 @@ describe('isTrustedBaseUrl', () => {
'https://api.minara.ai/',
'https://minara.ai',
'https://staging-api.minara.ai',
- 'http://localhost:3000',
- 'https://127.0.0.1:8443',
- 'http://[::1]:8080',
])('allows %s', (url) => {
expect(isTrustedBaseUrl(url)).toBe(true);
});
+ describe('loopback (local development)', () => {
+ const loopback = ['http://localhost:3000', 'https://127.0.0.1:8443', 'http://[::1]:8080'];
+ afterEach(() => { vi.unstubAllEnvs(); });
+
+ it.each(loopback)('rejects %s unless MINARA_DEV=1', (url) => {
+ vi.stubEnv('MINARA_DEV', '');
+ expect(isTrustedBaseUrl(url)).toBe(false);
+ vi.stubEnv('MINARA_DEV', '1');
+ expect(isTrustedBaseUrl(url)).toBe(true);
+ });
+
+ it('never allows plain http to a remote host, even in dev mode', () => {
+ vi.stubEnv('MINARA_DEV', '1');
+ expect(isTrustedBaseUrl('http://api.minara.ai')).toBe(false);
+ expect(isTrustedBaseUrl('https://evil.example')).toBe(false);
+ });
+ });
+
it.each([
'http://api.minara.ai', // plain http to a remote host
'https://evil.example',
@@ -83,3 +98,48 @@ describe('request() with an untrusted base URL', () => {
expect(() => getApiBaseUrl()).toThrow(/not a Minara host/);
});
});
+
+describe('response sanitization at the API boundary', () => {
+ const ESC = '\u001b';
+
+ it('strips terminal control sequences from every string but keeps line breaks', async () => {
+ fetchMock.mockResolvedValueOnce({
+ ok: true, status: 200,
+ text: async () => JSON.stringify({
+ data: {
+ name: `Wallet${ESC}[2K${ESC}]52;c;ZXZpbA==\u0007 \u202eevil`,
+ analysis: 'line 1\r\nline 2',
+ nested: [{ symbol: `ETH${ESC}[31m` }],
+ amount: 5,
+ },
+ }),
+ });
+ const res = await get>('/x', { token: 't' });
+ expect(res.data).toEqual({
+ name: 'Wallet evil',
+ analysis: 'line 1\nline 2',
+ nested: [{ symbol: 'ETH' }],
+ amount: 5,
+ });
+ });
+
+ it('sanitizes non-JSON error bodies', async () => {
+ fetchMock.mockResolvedValueOnce({ ok: false, status: 500, statusText: 'err', text: async () => `boom${ESC}[2J` });
+ const res = await get('/x', { token: 't' });
+ expect(res.error?.message).toBe('boom');
+ });
+
+ it('sanitizes Hyperliquid public API responses too', async () => {
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ json: async () => [
+ { universe: [{ name: `FAKE${ESC}[2K\nCOIN`, szDecimals: 2, maxLeverage: 5 }] },
+ [{ markPx: '1.5' }],
+ ],
+ });
+ const { getAssetMeta } = await import('../../src/api/perps.js');
+ const assets = await getAssetMeta();
+ expect(assets[0].name).toBe('FAKE COIN');
+ expect(assets[0].markPx).toBe(1.5);
+ });
+});
diff --git a/tests/api/perps.test.ts b/tests/api/perps.test.ts
index c21e893..0aa2a0e 100644
--- a/tests/api/perps.test.ts
+++ b/tests/api/perps.test.ts
@@ -310,7 +310,7 @@ describe('Hyperliquid API', () => {
expect(result).toEqual([{ name: 'ETH', maxLeverage: 50, szDecimals: 4, markPx: 2500 }]);
});
- it('getOpenOrders should POST to Hyperliquid info with openOrders and user', async () => {
+ it('getOpenOrders should POST to Hyperliquid info with frontendOpenOrders and user', async () => {
mockFetch.mockResolvedValueOnce({
json: vi.fn().mockResolvedValue([
{ coin: 'ETH', limitPx: '2500', oid: 1, side: 'B', sz: '0.1', timestamp: 1700000000 },
@@ -320,7 +320,7 @@ describe('Hyperliquid API', () => {
expect(mockFetch).toHaveBeenCalledWith('https://api.hyperliquid.xyz/info', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ type: 'openOrders', user: '0xUserAddr' }),
+ body: JSON.stringify({ type: 'frontendOpenOrders', user: '0xUserAddr' }),
});
expect(result).toHaveLength(1);
expect(result[0].coin).toBe('ETH');
diff --git a/tests/commands/limit-order.test.ts b/tests/commands/limit-order.test.ts
index 15503c2..cc466c1 100644
--- a/tests/commands/limit-order.test.ts
+++ b/tests/commands/limit-order.test.ts
@@ -96,3 +96,56 @@ describe('limit-order create chain validation', () => {
expect(createApi).toHaveBeenCalledWith('test-token', expect.objectContaining({ chain: 'solana' }));
});
});
+
+describe('limit-order cancel (M-316)', () => {
+ const ORDER = {
+ id: 'lo-123456789012345', chain: 'solana', side: 'sell', amount: '50', priceCondition: 'below',
+ targetPrice: 0.00002, targetTokenCA: 'DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263', status: 'active',
+ };
+
+ async function freshCancel() {
+ vi.resetModules();
+ const utils = await import('../../src/utils.js');
+ const api = await import('../../src/api/limitorder.js');
+ const touch = await import('../../src/touchid.js');
+ const { limitOrderCommand } = await import('../../src/commands/limit-order.js');
+ const cancelCmd = limitOrderCommand.commands.find((c) => c.name() === 'cancel')!;
+ return {
+ cancelCmd,
+ txConfirm: vi.mocked(utils.requireTransactionConfirmation),
+ touchId: vi.mocked(touch.requireTouchId),
+ listApi: vi.mocked(api.listLimitOrders),
+ cancelApi: vi.mocked(api.cancelLimitOrder),
+ };
+ }
+
+ it('shows the order in a transaction confirmation, then asks for Touch ID', async () => {
+ const { cancelCmd, txConfirm, touchId, listApi, cancelApi } = await freshCancel();
+ listApi.mockResolvedValue({ success: true, data: [ORDER] as never });
+ cancelApi.mockResolvedValue({ success: true, data: {} as never });
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+
+ await cancelCmd.parseAsync([ORDER.id], { from: 'user' });
+
+ expect(txConfirm).toHaveBeenCalledOnce();
+ const details = txConfirm.mock.calls[0][2];
+ expect(details?.chain).toBe('solana');
+ expect(details?.extra).toContainEqual(['Trigger', 'price below $0.00002']);
+ expect(details?.extra).toContainEqual(['Token', ORDER.targetTokenCA]);
+ expect(touchId.mock.invocationCallOrder[0]).toBeLessThan(cancelApi.mock.invocationCallOrder[0]);
+ expect(cancelApi).toHaveBeenCalledWith('test-token', ORDER.id);
+ });
+
+ it('-y skips the confirmation prompt but never Touch ID', async () => {
+ const { cancelCmd, txConfirm, touchId, listApi, cancelApi } = await freshCancel();
+ listApi.mockResolvedValue({ success: true, data: [ORDER] as never });
+ cancelApi.mockResolvedValue({ success: true, data: {} as never });
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+
+ await cancelCmd.parseAsync([ORDER.id, '-y'], { from: 'user' });
+
+ expect(txConfirm).not.toHaveBeenCalled();
+ expect(touchId).toHaveBeenCalledOnce();
+ expect(cancelApi).toHaveBeenCalled();
+ });
+});
diff --git a/tests/commands/logout.test.ts b/tests/commands/logout.test.ts
new file mode 100644
index 0000000..0add0c7
--- /dev/null
+++ b/tests/commands/logout.test.ts
@@ -0,0 +1,109 @@
+/**
+ * Integration tests for the logout command (M-352): a failed server-side
+ * revocation must not be reported as a successful logout.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+vi.mock('../../src/config.js', () => ({
+ loadCredentials: vi.fn(),
+ clearCredentials: vi.fn(),
+ loadConfig: () => ({ baseUrl: 'https://api.minara.ai' }),
+}));
+
+vi.mock('../../src/api/auth.js', () => ({
+ logout: vi.fn(),
+}));
+
+vi.mock('@inquirer/prompts', () => ({
+ confirm: vi.fn(),
+}));
+
+vi.mock('ora', () => ({
+ default: () => ({ start: () => ({ stop: () => {}, succeed: () => {}, text: '' }) }),
+}));
+
+async function fresh() {
+ vi.resetModules();
+ const config = await import('../../src/config.js');
+ const auth = await import('../../src/api/auth.js');
+ const { logoutCommand } = await import('../../src/commands/logout.js');
+ return {
+ logoutCommand,
+ loadCreds: vi.mocked(config.loadCredentials),
+ clearCreds: vi.mocked(config.clearCredentials),
+ logoutApi: vi.mocked(auth.logout),
+ };
+}
+
+let logs: string[];
+let errors: string[];
+let exitSpy: ReturnType;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ logs = [];
+ errors = [];
+ vi.spyOn(console, 'log').mockImplementation((...a) => { logs.push(a.join(' ')); });
+ vi.spyOn(console, 'error').mockImplementation((...a) => { errors.push(a.join(' ')); });
+ exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => { throw new Error('exit'); }) as never);
+});
+
+afterEach(() => exitSpy.mockRestore());
+
+describe('logout', () => {
+ it('revokes the server session, then clears local credentials', async () => {
+ const { logoutCommand, loadCreds, clearCreds, logoutApi } = await fresh();
+ loadCreds.mockReturnValue({ accessToken: 'tok' });
+ logoutApi.mockResolvedValue({ success: true });
+
+ await logoutCommand.parseAsync(['-y'], { from: 'user' });
+
+ expect(logoutApi).toHaveBeenCalledWith('tok');
+ expect(clearCreds).toHaveBeenCalledOnce();
+ expect(logs.join('\n')).toContain('server session revoked');
+ });
+
+ it('keeps local credentials and fails when the server could not revoke the session', async () => {
+ const { logoutCommand, loadCreds, clearCreds, logoutApi } = await fresh();
+ loadCreds.mockReturnValue({ accessToken: 'tok' });
+ logoutApi.mockResolvedValue({ success: false, error: { code: 503, message: 'Service Unavailable' } });
+
+ await expect(logoutCommand.parseAsync(['-y'], { from: 'user' })).rejects.toThrow('exit');
+
+ expect(clearCreds).not.toHaveBeenCalled();
+ expect(errors.join('\n')).toContain('Could not revoke your session on the server (Service Unavailable)');
+ expect(logs.join('\n')).not.toMatch(/Logged out/);
+ });
+
+ it('treats a network error like a failed revocation', async () => {
+ const { logoutCommand, loadCreds, clearCreds, logoutApi } = await fresh();
+ loadCreds.mockReturnValue({ accessToken: 'tok' });
+ logoutApi.mockRejectedValue(new Error('fetch failed'));
+
+ await expect(logoutCommand.parseAsync(['-y'], { from: 'user' })).rejects.toThrow('exit');
+
+ expect(clearCreds).not.toHaveBeenCalled();
+ expect(errors.join('\n')).toContain('fetch failed');
+ });
+
+ it('--local clears local credentials anyway, with a warning', async () => {
+ const { logoutCommand, loadCreds, clearCreds, logoutApi } = await fresh();
+ loadCreds.mockReturnValue({ accessToken: 'tok' });
+ logoutApi.mockResolvedValue({ success: false, error: { code: 503, message: 'Service Unavailable' } });
+
+ await logoutCommand.parseAsync(['-y', '--local'], { from: 'user' });
+
+ expect(clearCreds).toHaveBeenCalledOnce();
+ expect(logs.join('\n')).toContain('stays valid until it expires');
+ });
+
+ it('an already-expired session (401) counts as logged out', async () => {
+ const { logoutCommand, loadCreds, clearCreds, logoutApi } = await fresh();
+ loadCreds.mockReturnValue({ accessToken: 'tok' });
+ logoutApi.mockResolvedValue({ success: false, error: { code: 401, message: 'Unauthorized' } });
+
+ await logoutCommand.parseAsync(['-y'], { from: 'user' });
+
+ expect(clearCreds).toHaveBeenCalledOnce();
+ });
+});
diff --git a/tests/commands/perps.test.ts b/tests/commands/perps.test.ts
index a6fb947..a2ce31a 100644
--- a/tests/commands/perps.test.ts
+++ b/tests/commands/perps.test.ts
@@ -947,6 +947,12 @@ describe('buildQuickOrderPlan', () => {
.toEqual({ markPx: 3500, size: 2.8571, capped: true });
});
+ it('refuses an order worth less than the $10 Hyperliquid minimum', async () => {
+ const { buildQuickOrderPlan } = await import('../../src/commands/perps.js');
+ const res = buildQuickOrderPlan({ entryPrice: 3500, size: 0.002 }, META, 1000, 10);
+ expect((res as { error: string }).error).toMatch(/below Hyperliquid's \$10 minimum/);
+ });
+
it('keeps a smaller AI size', async () => {
const { buildQuickOrderPlan } = await import('../../src/commands/perps.js');
expect(buildQuickOrderPlan({ entryPrice: 3490, size: 0.5 }, META, 1000, 10))
@@ -984,7 +990,7 @@ describe('perps ask quick order', () => {
expect(vi.mocked(perpsApi.placeOrders)).toHaveBeenCalledOnce();
const order = vi.mocked(perpsApi.placeOrders).mock.calls[0][1].orders[0];
- expect(order).toMatchObject({ a: 'ETH', b: true, s: '2.8571', p: (3500 * 1.01).toPrecision(5) });
+ expect(order).toMatchObject({ a: 'ETH', b: true, s: '2.8571', p: '3535' });
expect(order.t).toEqual({ limit: { tif: 'Ioc' } });
expect(vi.mocked(utils.requireTransactionConfirmation)).toHaveBeenCalledOnce();
});
@@ -1033,7 +1039,8 @@ describe('perps close / order execution', () => {
expect(vi.mocked(perpsApi.placeOrders)).toHaveBeenCalledOnce();
const order = vi.mocked(perpsApi.placeOrders).mock.calls[0][1].orders[0];
// Closing a long = sell, reduce-only, bounded 1% below mark, immediate-or-cancel
- expect(order).toMatchObject({ a: 'ETH', b: false, r: true, s: '0.5', p: (3500 * 0.99).toPrecision(5) });
+ // No trailing zero: "3465.0" would change the signed payload and be rejected
+ expect(order).toMatchObject({ a: 'ETH', b: false, r: true, s: '0.5', p: '3465' });
expect(order.t).toEqual({ limit: { tif: 'Ioc' } });
});
@@ -1042,7 +1049,7 @@ describe('perps close / order execution', () => {
await cmd.parseAsync(['-S', 'long', '-s', 'ETH', '-z', '0.1', '-y'], { from: 'user' });
const order = vi.mocked(perpsApi.placeOrders).mock.calls[0][1].orders[0];
- expect(order).toMatchObject({ a: 'ETH', b: true, s: '0.1', p: (3500 * 1.01).toPrecision(5) });
+ expect(order).toMatchObject({ a: 'ETH', b: true, s: '0.1', p: '3535' });
expect(order.t).toEqual({ limit: { tif: 'Ioc' } });
});
@@ -1057,6 +1064,208 @@ describe('perps close / order execution', () => {
exitSpy.mockRestore();
});
+ const STOP_ORDER = {
+ coin: 'ETH', side: 'A', limitPx: '3000', sz: '0.5', oid: 42, timestamp: 1,
+ orderType: 'Stop Market', reduceOnly: true, isTrigger: true, triggerPx: '3050',
+ };
+
+ it('cancel: uses transaction confirmation and Touch ID, and warns when the order protects a position (M-316)', async () => {
+ vi.mocked(perpsApi.getPerpsAddress).mockResolvedValue('0xAAA');
+ vi.mocked(perpsApi.getOpenOrders).mockResolvedValue([STOP_ORDER] as never);
+ mockSelect.mockImplementationOnce((async (cfg: { choices: { value: unknown }[] }) => cfg.choices[0].value) as never);
+ vi.mocked(perpsApi.cancelOrders).mockResolvedValue({ success: true, data: {} as never });
+ const logs: string[] = [];
+ vi.mocked(console.log).mockImplementation((...a) => { logs.push(a.join(' ')); });
+
+ const cmd = await getCmd('cancel');
+ const utils = await import('../../src/utils.js');
+ const touch = await import('../../src/touchid.js');
+ await cmd.parseAsync([], { from: 'user' });
+
+ expect(logs.join('\n')).toContain('protects an open ETH position');
+ const txConfirm = vi.mocked(utils.requireTransactionConfirmation);
+ expect(txConfirm).toHaveBeenCalledOnce();
+ expect(txConfirm.mock.calls[0][2]?.extra).toContainEqual(['Order type', 'Stop Market · reduce-only · trigger $3,050']);
+ expect(mockConfirm).not.toHaveBeenCalled(); // single confirmation
+ const cancel = vi.mocked(perpsApi.cancelOrders);
+ expect(cancel).toHaveBeenCalledWith('test-token', expect.objectContaining({ cancels: [{ a: 'ETH', o: 42 }] }));
+ expect(vi.mocked(touch.requireTouchId).mock.invocationCallOrder[0]).toBeLessThan(cancel.mock.invocationCallOrder[0]);
+ });
+
+ it('cancel -y skips the confirmation prompt but never Touch ID', async () => {
+ vi.mocked(perpsApi.getPerpsAddress).mockResolvedValue('0xAAA');
+ vi.mocked(perpsApi.getOpenOrders).mockResolvedValue([STOP_ORDER] as never);
+ mockSelect.mockImplementationOnce((async (cfg: { choices: { value: unknown }[] }) => cfg.choices[0].value) as never);
+ vi.mocked(perpsApi.cancelOrders).mockResolvedValue({ success: true, data: {} as never });
+
+ const cmd = await getCmd('cancel');
+ const utils = await import('../../src/utils.js');
+ const touch = await import('../../src/touchid.js');
+ await cmd.parseAsync(['-y'], { from: 'user' });
+
+ expect(vi.mocked(utils.requireTransactionConfirmation)).not.toHaveBeenCalled();
+ expect(vi.mocked(touch.requireTouchId)).toHaveBeenCalledOnce();
+ });
+
+ it('order: a sub-wallet order shows that wallet\'s leverage, not the default wallet\'s', async () => {
+ mockListSubAccounts.mockResolvedValue({ success: true, data: [WALLET_DEFAULT, WALLET_SUB1] as never });
+ vi.mocked(perpsApi.getUserLeverage).mockImplementation(async (addr: string) => (addr === '0xBBB'
+ ? [{ coin: 'ETH', leverageValue: 3, leverageType: 'isolated' }]
+ : [{ coin: 'ETH', leverageValue: 20, leverageType: 'cross' }]) as never);
+
+ const cmd = await getCmd('order');
+ const utils = await import('../../src/utils.js');
+ await cmd.parseAsync(['-w', 'Bot-1', '-S', 'long', '-s', 'ETH', '-z', '0.1'], { from: 'user' });
+
+ expect(vi.mocked(perpsApi.getUserLeverage)).toHaveBeenCalledWith('0xBBB');
+ expect(vi.mocked(perpsApi.getUserLeverage)).not.toHaveBeenCalledWith('0xAAA');
+ expect(vi.mocked(perpsApi.getPerpsAddress)).not.toHaveBeenCalled();
+ const details = vi.mocked(utils.requireTransactionConfirmation).mock.calls[0][2];
+ expect(details?.extra).toContainEqual(['Leverage', '3x (isolated)']);
+ expect(details?.extra).toContainEqual(['Wallet', 'Bot-1']);
+ });
+
+ // Hyperliquid answers status "ok" even when an individual order is rejected
+ const hlOrderRes = (statuses: unknown[]) => ({
+ success: true, data: { status: 'ok', response: { type: 'order', data: { statuses } } } as never,
+ });
+ const IOC_NO_FILL = 'Order could not immediately match against any resting orders. asset=1';
+
+ function captureOutput() {
+ const logs: string[] = [];
+ const errors: string[] = [];
+ vi.spyOn(console, 'log').mockImplementation((...a) => { logs.push(a.join(' ')); });
+ vi.spyOn(console, 'error').mockImplementation((...a) => { errors.push(a.join(' ')); });
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => { throw new Error('exit'); }) as never);
+ return { logs, errors, exitSpy };
+ }
+
+ it('order: reports the fill size and price returned by Hyperliquid', async () => {
+ vi.mocked(perpsApi.placeOrders).mockResolvedValue(hlOrderRes([{ filled: { totalSz: '0.1', avgPx: '3501.2', oid: 1 } }]));
+ const { logs, exitSpy } = captureOutput();
+
+ const cmd = await getCmd('order');
+ await cmd.parseAsync(['-S', 'long', '-s', 'ETH', '-z', '0.1', '-y'], { from: 'user' });
+
+ expect(logs.join('\n')).toContain('Filled 0.1 ETH @ $3501.2');
+ exitSpy.mockRestore();
+ });
+
+ it('order: an IOC order that finds no liquidity fails instead of saying "submitted"', async () => {
+ vi.mocked(perpsApi.placeOrders).mockResolvedValue(hlOrderRes([{ error: IOC_NO_FILL }]));
+ const { logs, errors, exitSpy } = captureOutput();
+
+ const cmd = await getCmd('order');
+ await expect(cmd.parseAsync(['-S', 'long', '-s', 'ETH', '-z', '0.1', '-y'], { from: 'user' })).rejects.toThrow('exit');
+
+ expect(errors.join('\n')).toContain(`Hyperliquid rejected the order: ${IOC_NO_FILL}`);
+ expect(logs.join('\n')).not.toMatch(/submitted|Filled/);
+ exitSpy.mockRestore();
+ });
+
+ it('order: warns when an IOC order is only partly filled', async () => {
+ vi.mocked(perpsApi.placeOrders).mockResolvedValue(hlOrderRes([{ filled: { totalSz: '0.04', avgPx: '3501', oid: 1 } }]));
+ const { logs, exitSpy } = captureOutput();
+
+ const cmd = await getCmd('order');
+ await cmd.parseAsync(['-S', 'long', '-s', 'ETH', '-z', '0.1', '-y'], { from: 'user' });
+
+ expect(logs.join('\n')).toContain('Only 0.04 of 0.1 filled');
+ exitSpy.mockRestore();
+ });
+
+ it('order: BTC above $100k is priced without exponent notation', async () => {
+ mockGetAssetMeta.mockResolvedValue([{ name: 'BTC', maxLeverage: 40, szDecimals: 5, markPx: 101000 }]);
+ const cmd = await getCmd('order');
+ await cmd.parseAsync(['-S', 'long', '-s', 'BTC', '-z', '0.00020', '-y'], { from: 'user' });
+
+ const order = vi.mocked(perpsApi.placeOrders).mock.calls[0][1].orders[0];
+ // (101000 * 1.01).toPrecision(5) would be "1.0201e+5"
+ expect(order).toMatchObject({ a: 'BTC', b: true, p: '102010', s: '0.0002' });
+ });
+
+ it('order: rejects a size with more decimals than the asset allows, before submitting', async () => {
+ const { errors, exitSpy } = captureOutput();
+ const cmd = await getCmd('order');
+ await expect(cmd.parseAsync(['-S', 'long', '-s', 'ETH', '-z', '0.12345', '-y'], { from: 'user' })).rejects.toThrow('exit');
+
+ expect(errors.join('\n')).toContain('Size 0.12345 has more than 4 decimal place(s) for ETH');
+ expect(vi.mocked(perpsApi.placeOrders)).not.toHaveBeenCalled();
+ exitSpy.mockRestore();
+ });
+
+ it('order: rejects orders under the $10 minimum, before submitting', async () => {
+ const { errors, exitSpy } = captureOutput();
+ const cmd = await getCmd('order');
+ await expect(cmd.parseAsync(['-S', 'long', '-s', 'ETH', '-z', '0.002', '-y'], { from: 'user' })).rejects.toThrow('exit');
+
+ expect(errors.join('\n')).toContain("below Hyperliquid's $10 minimum");
+ expect(vi.mocked(perpsApi.placeOrders)).not.toHaveBeenCalled();
+ exitSpy.mockRestore();
+ });
+
+ it('order: a limit price off the tick grid is rejected with the nearest valid price', async () => {
+ mockGetAssetMeta.mockResolvedValue([{ name: 'BTC', maxLeverage: 40, szDecimals: 5, markPx: 97000 }]);
+ const { errors, exitSpy } = captureOutput();
+ const cmd = await getCmd('order');
+ await expect(cmd.parseAsync(['-S', 'long', '-s', 'BTC', '-T', 'limit', '-p', '97000.55', '-z', '0.001', '-y'], { from: 'user' }))
+ .rejects.toThrow('exit');
+
+ expect(errors.join('\n')).toContain('Price 97000.55 has more than 1 decimal place(s) for BTC on Hyperliquid (nearest valid: 97001)');
+ expect(vi.mocked(perpsApi.placeOrders)).not.toHaveBeenCalled();
+ exitSpy.mockRestore();
+ });
+
+ it('order: a valid limit price is sent without trailing zeros', async () => {
+ const cmd = await getCmd('order');
+ await cmd.parseAsync(['-S', 'long', '-s', 'ETH', '-T', 'limit', '-p', '3400.50', '-z', '0.0100', '-y'], { from: 'user' });
+
+ const order = vi.mocked(perpsApi.placeOrders).mock.calls[0][1].orders[0];
+ expect(order).toMatchObject({ p: '3400.5', s: '0.01' });
+ expect(order.t).toEqual({ limit: { tif: 'Gtc' } });
+ });
+
+ it('close: a rejected close is reported as a failure and exits non-zero', async () => {
+ vi.mocked(perpsApi.placeOrders).mockResolvedValue(hlOrderRes([{ error: IOC_NO_FILL }]));
+ const { logs, exitSpy } = captureOutput();
+
+ const cmd = await getCmd('close');
+ await cmd.parseAsync(['-s', 'ETH', '-y'], { from: 'user' });
+
+ const out = logs.join('\n');
+ expect(out).toContain('Failed to close 1 position(s)');
+ expect(out).toContain(IOC_NO_FILL);
+ expect(out).not.toContain('Closed 1 position(s)');
+ expect(process.exitCode).toBe(1);
+ process.exitCode = 0;
+ exitSpy.mockRestore();
+ });
+
+ it('close: a partial fill is not reported as closed', async () => {
+ vi.mocked(perpsApi.placeOrders).mockResolvedValue(hlOrderRes([{ filled: { totalSz: '0.2', avgPx: '3466', oid: 1 } }]));
+ const { logs, exitSpy } = captureOutput();
+
+ const cmd = await getCmd('close');
+ await cmd.parseAsync(['-s', 'ETH', '-y'], { from: 'user' });
+
+ expect(logs.join('\n')).toContain('only 0.2 of 0.5 filled; part of the position is still open');
+ expect(process.exitCode).toBe(1);
+ process.exitCode = 0;
+ exitSpy.mockRestore();
+ });
+
+ it('close: a full fill is reported as closed', async () => {
+ vi.mocked(perpsApi.placeOrders).mockResolvedValue(hlOrderRes([{ filled: { totalSz: '0.5', avgPx: '3466', oid: 1 } }]));
+ const { logs, exitSpy } = captureOutput();
+
+ const cmd = await getCmd('close');
+ await cmd.parseAsync(['-s', 'ETH', '-y'], { from: 'user' });
+
+ expect(logs.join('\n')).toContain('Closed 1 position(s)');
+ expect(process.exitCode ?? 0).toBe(0);
+ exitSpy.mockRestore();
+ });
+
it('sweep: uses the live withdrawable balance, not the cached wallet equity', async () => {
mockListSubAccounts.mockResolvedValue({ success: true, data: [WALLET_DEFAULT, WALLET_SUB1] as never });
mockGetStrategies.mockResolvedValue({ success: true, data: [] as never });
diff --git a/tests/commands/swap.test.ts b/tests/commands/swap.test.ts
index de55e76..476a7db 100644
--- a/tests/commands/swap.test.ts
+++ b/tests/commands/swap.test.ts
@@ -183,18 +183,122 @@ describe('swap quote preview', () => {
expect(txConfirm).toHaveBeenCalledOnce();
});
- it('does not fetch a quote with -y (no prompt to inform)', async () => {
+ function captureExit() {
+ const errors: string[] = [];
+ vi.spyOn(console, 'error').mockImplementation((...a) => { errors.push(a.join(' ')); });
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => { throw new Error('exit'); }) as never);
+ return { errors, exitSpy };
+ }
+
+ it('fetches and shows the quote with -y too (M-337 / M-348)', async () => {
const { swapCommand, lookup, swapsApi, simulateApi } = await fresh();
lookup.mockResolvedValueOnce({ symbol: 'BONK', name: 'Bonk', address: 'DezX', chain: 'solana' });
+ simulateApi.mockResolvedValue({ success: true, data: [SIM_RESULT] as never });
swapsApi.mockResolvedValue({ success: true, data: [{ txId: 'tx' }] });
- vi.spyOn(console, 'log').mockImplementation(() => {});
+ const logs: string[] = [];
+ vi.spyOn(console, 'log').mockImplementation((...a) => { logs.push(a.join(' ')); });
await swapCommand.parseAsync(['-s', 'buy', '-t', '$BONK', '-a', '100', '-y'], { from: 'user' });
- expect(simulateApi).not.toHaveBeenCalled();
+ expect(logs.join('\n')).toContain('Slippage');
+ expect(simulateApi.mock.invocationCallOrder[0]).toBeLessThan(swapsApi.mock.invocationCallOrder[0]);
+ });
+
+ it('never sends an unattended (-y) swap without a quote', async () => {
+ const { swapCommand, lookup, swapsApi, simulateApi } = await fresh();
+ lookup.mockResolvedValueOnce({ symbol: 'BONK', name: 'Bonk', address: 'DezX', chain: 'solana' });
+ simulateApi.mockResolvedValue({ success: false, error: { code: 500, message: 'down' } });
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const { errors, exitSpy } = captureExit();
+
+ await expect(swapCommand.parseAsync(['-s', 'buy', '-t', '$BONK', '-a', '100', '-y'], { from: 'user' }))
+ .rejects.toThrow('exit');
+ expect(errors.join('\n')).toContain('could not fetch a quote');
+ expect(swapsApi).not.toHaveBeenCalled();
+ exitSpy.mockRestore();
+ });
+
+ it('refuses a quote whose slippage tolerance is above the limit (M-333)', async () => {
+ const { swapCommand, lookup, txConfirm, swapsApi, simulateApi } = await fresh();
+ lookup.mockResolvedValueOnce({ symbol: 'BONK', name: 'Bonk', address: 'DezX', chain: 'solana' });
+ simulateApi.mockResolvedValue({ success: true, data: [{ ...SIM_RESULT, slippageBps: 1500 }] as never });
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const { errors, exitSpy } = captureExit();
+
+ await expect(swapCommand.parseAsync(['-s', 'buy', '-t', '$BONK', '-a', '100'], { from: 'user' }))
+ .rejects.toThrow('exit');
+ expect(errors.join('\n')).toContain('quoted slippage tolerance 15% is above the 10% limit');
+ expect(txConfirm).not.toHaveBeenCalled();
+ expect(swapsApi).not.toHaveBeenCalled();
+ exitSpy.mockRestore();
+ });
+
+ it('--max-slippage raises the limit', async () => {
+ const { swapCommand, lookup, txConfirm, swapsApi, simulateApi } = await fresh();
+ lookup.mockResolvedValueOnce({ symbol: 'BONK', name: 'Bonk', address: 'DezX', chain: 'solana' });
+ simulateApi.mockResolvedValue({ success: true, data: [{ ...SIM_RESULT, slippageBps: 1500 }] as never });
+ swapsApi.mockResolvedValue({ success: true, data: [{ txId: 'tx' }] });
+ txConfirm.mockResolvedValue(undefined);
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+
+ await swapCommand.parseAsync(['-s', 'buy', '-t', '$BONK', '-a', '100', '--max-slippage', '20'], { from: 'user' });
+
expect(swapsApi).toHaveBeenCalled();
});
+ it('refuses a quote whose price impact is above the limit, even with -y', async () => {
+ const { swapCommand, lookup, swapsApi, simulateApi } = await fresh();
+ lookup.mockResolvedValueOnce({ symbol: 'BONK', name: 'Bonk', address: 'DezX', chain: 'solana' });
+ simulateApi.mockResolvedValue({ success: true, data: [{ ...SIM_RESULT, priceImpact: '25.4' }] as never });
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const { errors, exitSpy } = captureExit();
+
+ await expect(swapCommand.parseAsync(['-s', 'buy', '-t', '$BONK', '-a', '100', '-y'], { from: 'user' }))
+ .rejects.toThrow('exit');
+ expect(errors.join('\n')).toContain('quoted price impact 25.4% is above the 10% limit');
+ expect(swapsApi).not.toHaveBeenCalled();
+ exitSpy.mockRestore();
+ });
+
+ it('with -y --json the quote is not printed (stdout stays one JSON result) but still checked', async () => {
+ const { swapCommand, lookup, swapsApi, simulateApi } = await fresh();
+ const formatters = await import('../../src/formatters.js');
+ formatters.setRawJson(true);
+ lookup.mockResolvedValueOnce({ symbol: 'BONK', name: 'Bonk', address: 'DezX', chain: 'solana' });
+ simulateApi.mockResolvedValue({ success: true, data: [SIM_RESULT] as never });
+ swapsApi.mockResolvedValue({ success: true, data: [{ txId: 'tx' }] });
+ const logs: string[] = [];
+ vi.spyOn(console, 'log').mockImplementation((...a) => { logs.push(a.join(' ')); });
+
+ try {
+ await swapCommand.parseAsync(['-s', 'buy', '-t', '$BONK', '-a', '100', '-y'], { from: 'user' });
+ } finally {
+ formatters.setRawJson(false);
+ }
+ expect(simulateApi).toHaveBeenCalled();
+ expect(logs.join('\n')).not.toContain('slippageBps');
+ });
+
+ it('quoteLimitError', async () => {
+ const { quoteLimitError } = await import('../../src/commands/swap.js');
+ const limits = { maxSlippagePct: 10, maxPriceImpactPct: 10 };
+ expect(quoteLimitError(SIM_RESULT as never, limits)).toBeNull();
+ expect(quoteLimitError({ ...SIM_RESULT, priceImpact: '-1' } as never, limits)).toBeNull(); // negligible
+ expect(quoteLimitError({ ...SIM_RESULT, priceImpact: null } as never, limits)).toBeNull();
+ expect(quoteLimitError({ ...SIM_RESULT, slippageBps: 1001 } as never, limits)).toMatch(/10.01%/);
+ expect(quoteLimitError({ error: 'NO_ROUTE', message: 'no route' } as never, limits)).toBe('the quote failed: no route');
+ });
+
+ it('rejects an invalid --max-slippage', async () => {
+ const { swapCommand } = await fresh();
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const { errors, exitSpy } = captureExit();
+ await expect(swapCommand.parseAsync(['-s', 'buy', '-t', '$BONK', '-a', '100', '--max-slippage', '1e9'], { from: 'user' }))
+ .rejects.toThrow('exit');
+ expect(errors.join('\n')).toContain('--max-slippage must be a percentage');
+ exitSpy.mockRestore();
+ });
+
it('rejects --chain that does not match the token', async () => {
const { swapCommand, lookup, swapsApi } = await fresh();
lookup.mockResolvedValueOnce({ symbol: 'BONK', name: 'Bonk', address: 'DezX', chain: 'solana' });
diff --git a/tests/config.test.ts b/tests/config.test.ts
index 442bf4d..226a20e 100644
--- a/tests/config.test.ts
+++ b/tests/config.test.ts
@@ -188,6 +188,47 @@ describe('config module', () => {
expect(cfg.baseUrl).toBe('https://custom.api.com');
});
+ it('flags a truncated config instead of silently dropping its settings (M-353)', async () => {
+ const dir = join(tempDir, '.minara');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'config.json'), '{"touchId": true, "confirmBefore');
+ const { loadConfig } = await importConfig();
+
+ const cfg = loadConfig();
+ expect(cfg.loadError).toMatch(/could not read/);
+ expect(cfg.baseUrl).toBe('https://api.minara.ai');
+ });
+
+ it('flags a config that is not a JSON object', async () => {
+ const dir = join(tempDir, '.minara');
+ mkdirSync(dir, { recursive: true });
+ const { loadConfig } = await importConfig();
+ for (const raw of ['null', '[]', '42']) {
+ writeFileSync(join(dir, 'config.json'), raw);
+ expect(loadConfig().loadError, raw).toMatch(/does not contain a JSON object/);
+ }
+ });
+
+ it('never stores loadError, and saving over a damaged file repairs it', async () => {
+ const dir = join(tempDir, '.minara');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'config.json'), '{"touch');
+ const { saveConfig, loadConfig } = await importConfig();
+
+ saveConfig({ touchId: true, loadError: 'should not be saved' });
+ const saved = JSON.parse(readFileSync(join(dir, 'config.json'), 'utf-8'));
+ expect(saved.loadError).toBeUndefined();
+ expect(saved.touchId).toBe(true);
+ expect(loadConfig().loadError).toBeUndefined();
+ });
+
+ it('writes atomically: no temp files are left behind', async () => {
+ const { saveConfig, saveCredentials } = await importConfig();
+ saveConfig({ touchId: false });
+ saveCredentials({ accessToken: 'tok' });
+ const { readdirSync } = await import('node:fs');
+ expect(readdirSync(join(tempDir, '.minara')).sort()).toEqual(['config.json', 'credentials.json']);
+ });
});
// ── File permissions ────────────────────────────────────────────────
diff --git a/tests/hl-format.test.ts b/tests/hl-format.test.ts
new file mode 100644
index 0000000..ce0f9dc
--- /dev/null
+++ b/tests/hl-format.test.ts
@@ -0,0 +1,149 @@
+import { describe, it, expect } from 'vitest';
+import {
+ canonicalDecimal, extractOrderStatuses, formatHlPrice, formatHlSize,
+ hlPriceError, hlSizeError, isPositiveDecimal, marketOrderPrice,
+} from '../src/hl-format.js';
+
+// Rules: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/tick-and-lot-size
+
+describe('formatHlPrice', () => {
+ it('never uses exponent notation (prices of 100,000 and above)', () => {
+ // (101000 * 1.01).toPrecision(5) === "1.0201e+5", which is not a valid wire price
+ expect(formatHlPrice(102010.5, 5)).toBe('102010');
+ expect(marketOrderPrice(101000, true, 5)).toBe('102010');
+ expect(marketOrderPrice(101000, false, 5)).toBe('99990');
+ });
+
+ it('drops trailing zeros (they change the signed payload)', () => {
+ expect(formatHlPrice(3535, 4)).toBe('3535');
+ expect(marketOrderPrice(3500, true, 4)).toBe('3535');
+ expect(marketOrderPrice(3500, false, 4)).toBe('3465');
+ });
+
+ it('keeps at most 5 significant figures', () => {
+ expect(formatHlPrice(97000.55, 5)).toBe('97001');
+ expect(formatHlPrice(3456.789, 4)).toBe('3456.8');
+ });
+
+ it('keeps at most 6 - szDecimals decimal places', () => {
+ // 5 significant figures would be 0.12468, but szDecimals 2 allows 4 decimals
+ expect(formatHlPrice(0.1246845, 2)).toBe('0.1247');
+ expect(formatHlPrice(0.00123456, 0)).toBe('0.001235');
+ expect(formatHlPrice(0.012345678, 0)).toBe('0.012346');
+ });
+
+ it('rejects prices that are not positive or below the smallest tick', () => {
+ expect(() => formatHlPrice(0, 2)).toThrow();
+ expect(() => formatHlPrice(Number.NaN, 2)).toThrow();
+ expect(() => formatHlPrice(0.000001, 4)).toThrow(/smallest tick/);
+ });
+
+ it('always produces a price Hyperliquid accepts, close to the input', () => {
+ const prices = [0.0000123, 0.00045678, 0.0123456, 0.987654, 1.23456, 7.654321, 23.45678,
+ 123.4567, 999.999, 3456.789, 12345.67, 99999.9, 101234.5, 987654.3];
+ for (const px of prices) {
+ for (let szDecimals = 0; szDecimals <= 5; szDecimals++) {
+ let out: string;
+ try { out = formatHlPrice(px, szDecimals); } catch { continue; } // too small for this lot size
+ expect(out, `${px} / ${szDecimals}`).toMatch(/^\d+(\.\d*[1-9])?$/);
+ expect(hlPriceError(out, szDecimals), `${px} / ${szDecimals} → ${out}`).toBeNull();
+ // Where the tick allows at least 4 significant digits, rounding stays well inside the 1% buffer
+ if (px * 10 ** (6 - szDecimals) >= 1000) {
+ expect(Math.abs(Number(out) - px) / px, `${px} / ${szDecimals} → ${out}`).toBeLessThan(0.001);
+ }
+ }
+ }
+ });
+});
+
+describe('hlPriceError', () => {
+ it('accepts valid prices', () => {
+ expect(hlPriceError('123456', 5)).toBeNull(); // integers are always valid
+ expect(hlPriceError('97001', 5)).toBeNull();
+ expect(hlPriceError('3456.8', 4)).toBeNull();
+ expect(hlPriceError('3456.80', 4)).toBeNull(); // trailing zeros are not significant
+ expect(hlPriceError('1234.5', 2)).toBeNull();
+ expect(hlPriceError('0.001234', 0)).toBeNull();
+ });
+
+ it('rejects too many decimals or significant figures', () => {
+ expect(hlPriceError('97000.55', 5)).toMatch(/more than 1 decimal/);
+ expect(hlPriceError('1234.56', 2)).toMatch(/5 significant figures/);
+ // Official example: 12345.6 is not valid (6 significant figures, not an integer)
+ expect(hlPriceError('12345.6', 0)).toMatch(/5 significant figures/);
+ expect(hlPriceError('0.0012345', 0)).toMatch(/more than 6 decimal/);
+ });
+
+ it('rejects anything that is not a plain positive decimal', () => {
+ for (const bad of ['1e3', '0x10', '-1', '0', '', ' ', '1,000', 'abc', 'Infinity']) {
+ expect(hlPriceError(bad, 2), bad).toMatch(/plain positive number/);
+ }
+ });
+});
+
+describe('sizes', () => {
+ it('hlSizeError enforces szDecimals', () => {
+ expect(hlSizeError('0.00023', 5)).toBeNull();
+ expect(hlSizeError('1.50', 1)).toBeNull();
+ expect(hlSizeError('0.000231', 5)).toMatch(/more than 5 decimal/);
+ expect(hlSizeError('1.55', 1)).toMatch(/more than 1 decimal/);
+ expect(hlSizeError('3', 0)).toBeNull();
+ expect(hlSizeError('0.5', 0)).toMatch(/more than 0 decimal/);
+ expect(hlSizeError('1e-3', 5)).toMatch(/plain positive number/);
+ });
+
+ it('formatHlSize rounds to szDecimals without trailing zeros', () => {
+ expect(formatHlSize(0.5, 4)).toBe('0.5');
+ expect(formatHlSize(2.8571, 4)).toBe('2.8571');
+ expect(formatHlSize(12, 2)).toBe('12');
+ expect(() => formatHlSize(0, 2)).toThrow();
+ expect(() => formatHlSize(Number.NaN, 2)).toThrow();
+ });
+
+ it('canonicalDecimal strips leading and trailing zeros', () => {
+ expect(canonicalDecimal('007.50')).toBe('7.5');
+ expect(canonicalDecimal('0.10')).toBe('0.1');
+ expect(canonicalDecimal('100.000')).toBe('100');
+ expect(canonicalDecimal('10')).toBe('10');
+ expect(canonicalDecimal('0.5')).toBe('0.5');
+ });
+
+ it('isPositiveDecimal', () => {
+ expect(isPositiveDecimal('0.1')).toBe(true);
+ expect(isPositiveDecimal('5')).toBe(true);
+ expect(isPositiveDecimal('0')).toBe(false);
+ expect(isPositiveDecimal('1e3')).toBe(false);
+ expect(isPositiveDecimal('0x10')).toBe(false);
+ });
+});
+
+describe('extractOrderStatuses', () => {
+ const hl = (statuses: unknown[]) => ({ status: 'ok', response: { type: 'order', data: { statuses } } });
+
+ it('reads Hyperliquid per-order statuses', () => {
+ expect(extractOrderStatuses(hl([{ filled: { totalSz: '0.1', avgPx: '3501.2', oid: 7 } }])))
+ .toEqual([{ kind: 'filled', totalSz: '0.1', avgPx: '3501.2' }]);
+ expect(extractOrderStatuses(hl([{ resting: { oid: 7 } }]))).toEqual([{ kind: 'resting', oid: 7 }]);
+ expect(extractOrderStatuses(hl([{ error: 'Order could not immediately match against any resting orders. asset=1' }])))
+ .toEqual([{ kind: 'error', message: 'Order could not immediately match against any resting orders. asset=1' }]);
+ expect(extractOrderStatuses(hl(['waitingForFill']))).toEqual([{ kind: 'other', value: 'waitingForFill' }]);
+ });
+
+ it('finds statuses wherever the backend nests them', () => {
+ expect(extractOrderStatuses({ result: hl([{ error: 'Order must have minimum value of $10.' }]) }))
+ .toEqual([{ kind: 'error', message: 'Order must have minimum value of $10.' }]);
+ expect(extractOrderStatuses({ statuses: [{ filled: { totalSz: '1', avgPx: '2' } }] }))
+ .toEqual([{ kind: 'filled', totalSz: '1', avgPx: '2' }]);
+ });
+
+ it('treats a top-level Hyperliquid error as a rejection', () => {
+ expect(extractOrderStatuses({ status: 'err', response: 'User or API Wallet 0xabc does not exist.' }))
+ .toEqual([{ kind: 'error', message: 'User or API Wallet 0xabc does not exist.' }]);
+ });
+
+ it('returns null when there is nothing to read', () => {
+ expect(extractOrderStatuses({})).toBeNull();
+ expect(extractOrderStatuses(undefined)).toBeNull();
+ expect(extractOrderStatuses('ok')).toBeNull();
+ });
+});
diff --git a/tests/security-hardening.test.ts b/tests/security-hardening.test.ts
index 4be72f6..2eaba38 100644
--- a/tests/security-hardening.test.ts
+++ b/tests/security-hardening.test.ts
@@ -15,10 +15,11 @@ vi.mock('@inquirer/prompts', () => ({
input: vi.fn(),
}));
-const configState: { confirmBeforeTransaction?: boolean; touchId?: boolean } = {};
+const configState: { confirmBeforeTransaction?: boolean; touchId?: boolean; loadError?: string } = {};
vi.mock('../src/config.js', () => ({
loadConfig: () => ({ baseUrl: 'https://api.minara.ai', ...configState }),
getMinaraDir: () => '/tmp/minara-test',
+ configLoadErrorMessage: (e: string) => `Your Minara config is damaged (${e}). Fund operations are blocked.`,
}));
const platformState = { value: 'linux' as NodeJS.Platform };
@@ -43,6 +44,11 @@ import {
assertTokenOnChain,
formatTokenLabel,
requireTransactionConfirmation,
+ base58Decode,
+ isSolanaAddress,
+ isOnEd25519Curve,
+ recipientAddressWarning,
+ validateAddress,
} from '../src/utils.js';
const ESC = '\u001b';
@@ -52,6 +58,7 @@ beforeEach(() => {
vi.clearAllMocks();
configState.confirmBeforeTransaction = undefined;
configState.touchId = undefined;
+ configState.loadError = undefined;
platformState.value = 'linux';
});
@@ -81,6 +88,20 @@ describe('sanitizeTerminal', () => {
expect(sanitizeTerminal('line1\r\nline2\rX\u0008', { multiline: true })).toBe('line1\nline2\nX');
});
+ it('removes invisible characters that make two strings look identical (M-332)', () => {
+ // zero-width space / non-joiner / joiner, word joiner, BOM, soft hyphen
+ expect(sanitizeTerminal('Dez\u200bX\u200c\u200d\u2060\ufeff\u00adB')).toBe('DezXB');
+ // combining grapheme joiner, Hangul filler, variation selector, interlinear annotation
+ expect(sanitizeTerminal('a\u034fb\u3164c\ufe0fd\ufff9e')).toBe('abcde');
+ // Unicode tag characters ("ASCII smuggling") and supplementary variation selectors
+ expect(sanitizeTerminal('ok\u{e0049}\u{e0067}\u{e006e}\u{e0101}!')).toBe('ok!');
+ });
+
+ it('treats Unicode line / paragraph separators and NEL as line breaks', () => {
+ expect(sanitizeTerminal('BONK\u2028Address : 0xEvil\u2029x\u0085y')).toBe('BONK Address : 0xEvil x y');
+ expect(sanitizeTerminal('a\u2028b', { multiline: true })).toBe('a\nb');
+ });
+
it('leaves ordinary text and unicode untouched', () => {
expect(sanitizeTerminal('$SOL — Solana 🚀 中文')).toBe('$SOL — Solana 🚀 中文');
});
@@ -119,6 +140,13 @@ describe('formatTokenLabel', () => {
// ─── Transaction confirmation output ─────────────────────────────────────
describe('requireTransactionConfirmation', () => {
+ it('refuses when config.json is damaged, even if confirmation looks disabled (M-353)', async () => {
+ configState.loadError = 'Unexpected end of JSON input';
+ configState.confirmBeforeTransaction = false;
+ await expect(requireTransactionConfirmation('Test')).rejects.toThrow(/config is damaged/);
+ expect(confirm).not.toHaveBeenCalled();
+ });
+
it('warns visibly when confirmation is disabled in config', async () => {
configState.confirmBeforeTransaction = false;
const logs: string[] = [];
@@ -221,6 +249,16 @@ describe('requireTouchId', () => {
await expect(requireTouchId()).resolves.toBeUndefined();
});
+ it('fails closed when config.json is damaged: Touch ID may have been on (M-353)', async () => {
+ configState.loadError = 'Unexpected end of JSON input';
+ const errors: string[] = [];
+ vi.mocked(console.error).mockImplementation((...a) => { errors.push(a.join(' ')); });
+ const { requireTouchId } = await import('../src/touchid.js');
+ await expect(requireTouchId()).rejects.toThrow('exit');
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ expect(errors.join('\n')).toContain('config is damaged');
+ });
+
it('cancels the operation when enabled on a non-macOS platform', async () => {
configState.touchId = true;
platformState.value = 'linux';
@@ -229,3 +267,43 @@ describe('requireTouchId', () => {
expect(exitSpy).toHaveBeenCalledWith(1);
});
});
+
+describe('sanitizeDeep multiline option', () => {
+ it('keeps \\n in values when multiline, but keys stay single-line', () => {
+ expect(sanitizeDeep({ 'a\nb': 'x\r\ny\u001b[2K' }, { multiline: true })).toEqual({ 'a b': 'x\ny' });
+ expect(sanitizeDeep({ k: 'x\ny' })).toEqual({ k: 'x y' });
+ });
+});
+
+describe('Solana recipient checks (M-351)', () => {
+ const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+
+ it('base58Decode', () => {
+ expect(base58Decode('11111111111111111111111111111111')).toEqual(new Uint8Array(32));
+ expect(base58Decode(USDC_MINT)?.length).toBe(32);
+ expect(base58Decode('0OIl')).toBeNull(); // not in the base58 alphabet
+ expect(Array.from(base58Decode('5Q')!)).toEqual([0xff]);
+ });
+
+ it('accepts only strings that decode to a 32-byte key', () => {
+ expect(isSolanaAddress(USDC_MINT)).toBe(true);
+ expect(isSolanaAddress('So11111111111111111111111111111111111111112')).toBe(true);
+ expect(isSolanaAddress(USDC_MINT.slice(0, 40))).toBe(false); // truncated: 30 bytes
+ expect(isSolanaAddress(USDC_MINT + 'v')).toBe(false); // too long: 33 bytes
+ expect(isSolanaAddress('HelloWorldThisIsNotAKeyButLooksBase58xx')).toBe(false);
+ expect(validateAddress(USDC_MINT.slice(0, 40), 'solana')).toMatch(/32-byte public key/);
+ });
+
+ it('isOnEd25519Curve tells wallet keys from off-curve values', () => {
+ expect(isOnEd25519Curve(base58Decode(USDC_MINT)!)).toBe(true);
+ expect(isOnEd25519Curve(base58Decode('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1z')!)).toBe(false);
+ expect(isOnEd25519Curve(new Uint8Array(31))).toBe(false);
+ });
+
+ it('warns (without blocking) about an off-curve Solana recipient', () => {
+ expect(recipientAddressWarning(USDC_MINT, 'solana')).toBeUndefined();
+ expect(recipientAddressWarning('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1z', 'solana')).toMatch(/not a wallet public key/);
+ expect(validateAddress('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1z', 'solana')).toBe(true);
+ expect(recipientAddressWarning('0x' + '1'.repeat(40), 'base')).toBeUndefined();
+ });
+});
diff --git a/tests/utils.test.ts b/tests/utils.test.ts
index 1fe1947..575aff3 100644
--- a/tests/utils.test.ts
+++ b/tests/utils.test.ts
@@ -307,7 +307,7 @@ describe('utils', () => {
it('should reject invalid Solana address', () => {
const msg = validateAddress('0x123', 'solana');
- expect(msg).toBe('Invalid Solana address (expected base58, 32–44 chars)');
+ expect(msg).toBe('Invalid Solana address (expected a base58-encoded 32-byte public key)');
});
it('should accept valid EVM address', () => {