From 409613093a30688d78bf5bd87fc6b4477a401504 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 17:33:20 +0800 Subject: [PATCH] fix: bind native placeholders to their chain; never replay writes after re-login MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit M-365: token lookup with a chain kept every EVM native placeholder (0x0…0 / 0xE…E) from any chain, relabelled it as the requested chain and kept its symbol, and assertTokenOnChain let placeholders through. `$POL --chain base` could therefore be confirmed as POL and executed as Base ETH; Solana accepted EVM placeholders too. - a placeholder entry is only kept when its symbol is the requested chain's native coin (ETH listed on Ethereum may be used on Base, POL may not); never on Solana; assertTokenOnChain enforces the same rule - placeholder entries are ranked and shown on the chain they execute on, so a foreign native entry no longer sorts ahead of real tokens - typing the placeholder itself with a chain resolves directly to that chain's native token M-366: after a 401 the interactive re-login replayed the original request whatever it was, and the same-account check only blocked when both identities were known and differed. - only read-only requests are retried: GET, plus POST endpoints marked `replayable` (swap quote, activities, statuses, price analysis); a trade, transfer, order, cancellation or account change is never re-sent, and the user re-runs the command to confirm it with current prices - the account check fails closed: user ids, else server-returned emails, must match; with nothing to compare there is no retry - after a same-account renewal, later requests of the same command use the new token instead of prompting again (they are sent for the first time after the re-login, not replayed) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0133E5DCA8sK7CJ7WWWrb2P7 --- README.md | 5 +- src/api/client.ts | 38 +++++- src/api/crosschain.ts | 5 +- src/api/perps.ts | 2 +- src/auth-refresh.ts | 97 +++++++++++---- src/utils.ts | 94 ++++++++++++--- tests/api/client-auth.test.ts | 122 ++++++++++--------- tests/api/crosschain.test.ts | 3 + tests/api/perps.test.ts | 2 +- tests/auth-refresh.test.ts | 201 ++++++++++++------------------- tests/lookup-token.test.ts | 53 ++++++++ tests/security-hardening.test.ts | 15 ++- 12 files changed, 408 insertions(+), 229 deletions(-) diff --git a/README.md b/README.md index ac422d1..02a25b5 100644 --- a/README.md +++ b/README.md @@ -398,7 +398,7 @@ minara --help ## Testing -Test suite built with [Vitest](https://vitest.dev/) — 425 tests covering unit, API, command integration, and formatter layers. +Test suite built with [Vitest](https://vitest.dev/) — 438 tests covering unit, API, command integration, and formatter layers. ```bash npm test # Run all tests @@ -413,8 +413,9 @@ npm run test:coverage # With v8 coverage report - **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` (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 +- **Native tokens per chain** — the native-token placeholder `0x0…0` / `0xE…E` always means the native coin of the selected chain. Lookup only offers it under that coin's symbol (for example `$ETH` on Base, never `$POL` on Base), and never on Solana - **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 +- **Re-login safety** — after an expired session the CLI offers to sign in again. Only read-only requests are then retried automatically, and only when the new session provably belongs to the same account. A trade, transfer, order or account change is never re-sent: run the command again to review and confirm it with current prices - 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 diff --git a/src/api/client.ts b/src/api/client.ts index e40d13e..ff0dbd7 100644 --- a/src/api/client.ts +++ b/src/api/client.ts @@ -12,6 +12,26 @@ interface RequestOptions { headers?: Record; /** Return a plain 401 instead of prompting to log in again (e.g. logout). */ noReauth?: boolean; + /** + * Safe to send again automatically after a re-login: the request has no + * side effects. Defaults to true for GET and false for everything else. + */ + replayable?: boolean; +} + +/** + * Tokens superseded by a re-login in this process, for the same account. + * Commands read the token once at start; later requests of the same command + * use the renewed token instead of hitting 401 and prompting again. These + * requests are sent for the first time after the re-login (and after any + * confirmation that follows it), so this is not a replay. + */ +const renewedTokens = new Map(); + +function currentToken(token: string | undefined): string | undefined { + let t = token; + for (let i = 0; t && renewedTokens.has(t) && i < 5; i++) t = renewedTokens.get(t); + return t; } // ── Base URL trust check ────────────────────────────────────────────────── @@ -92,7 +112,8 @@ async function requestImpl( opts: RequestOptions, isRetry: boolean, ): Promise> { - const { method = 'GET', body, query, token, headers: extraHeaders } = opts; + const { method = 'GET', body, query, headers: extraHeaders } = opts; + const token = currentToken(opts.token); let url: string; try { @@ -195,11 +216,20 @@ async function handleAuthExpired( try { // Dynamic import — only loaded when needed, avoids circular deps const { attemptReAuth } = await import('../auth-refresh.js'); - const newToken = await attemptReAuth(); + // Only reads are replayed. The rejected request was not executed, and a + // write (trade, transfer, order, account change) must go back through the + // command's confirmation with current quotes instead of being re-sent. + const outcome = await attemptReAuth({ replayable: opts.replayable ?? (opts.method ?? 'GET') === 'GET' }); - if (newToken) { + if (outcome.kind !== 'failed' && outcome.token && opts.token) { + renewedTokens.set(opts.token, outcome.token); // same account confirmed + } + if (outcome.kind === 'retry') { // Retry the original request with the new token (isRetry = true) - return requestImpl(path, { ...opts, token: newToken }, true); + return requestImpl(path, { ...opts, token: outcome.token }, true); + } + if (outcome.kind === 'renewed') { + return { success: false, error: { code: 401, message: outcome.message } }; } } catch (err) { // Module load failure or unexpected error — log for debugging, fall through diff --git a/src/api/crosschain.ts b/src/api/crosschain.ts index 29b4b21..15e09e7 100644 --- a/src/api/crosschain.ts +++ b/src/api/crosschain.ts @@ -35,6 +35,7 @@ export function swaps(token: string, swapList: CrossChainSwapDto[]) { /** Simulate swaps (dry-run) */ export function swapsSimulate(token: string, swapList: CrossChainSwapDto[]) { return post('/v1/tx/cross-chain/swaps-simulate', { + replayable: true, // quote only, no side effects token, body: { swaps: swapList }, }); @@ -47,7 +48,7 @@ export function transfer(token: string, dto: CrossChainTransferDto) { /** Get activities */ export function getActivities(token: string, dto: CrossChainActivitiesDto) { - return post[]>('/v1/tx/cross-chain/activities', { token, body: dto }); + return post[]>('/v1/tx/cross-chain/activities', { token, body: dto, replayable: true }); } /** Get PnL history */ @@ -57,5 +58,5 @@ export function getPnlHistory(token: string, type: string) { /** Check transaction statuses */ export function getStatuses(token: string, transactionIds: string[]) { - return post('/v1/tx/cross-chain/statuses', { token, body: { transactionIds } }); + return post('/v1/tx/cross-chain/statuses', { token, body: { transactionIds }, replayable: true }); } diff --git a/src/api/perps.ts b/src/api/perps.ts index 44785be..4390131 100644 --- a/src/api/perps.ts +++ b/src/api/perps.ts @@ -183,7 +183,7 @@ export function sweepFunds(token: string, dto: SweepFundsDto) { // ── Price Analysis (Ask Long/Short) ────────────────────────────────────── export function priceAnalysis(token: string, dto: { symbol: string; startTime?: number; endTime?: number; interval?: string; positionUSD?: number; leverage?: number }) { - return post>('/tokens/price-analysis', { token, body: dto }); + return post>('/tokens/price-analysis', { token, body: dto, replayable: true }); } /** Get perps wallet address from user profile */ diff --git a/src/auth-refresh.ts b/src/auth-refresh.ts index d0428e6..7ac19fe 100644 --- a/src/auth-refresh.ts +++ b/src/auth-refresh.ts @@ -13,18 +13,52 @@ import chalk from 'chalk'; import { loadCredentials, saveCredentials } from './config.js'; import { sendEmailCode, verifyEmailCode } from './api/auth.js'; +/** What happened after a 401, and whether the original request may be sent again. */ +export type ReAuthOutcome = + /** Same account confirmed and the request is a read: replay it with this token. */ + | { kind: 'retry'; token: string } + /** + * Signed in again (credentials saved) but the request must NOT be replayed. + * `token` is set only when the new session is the same account. + */ + | { kind: 'renewed'; message: string; token?: string } + /** Declined, cancelled or failed: nothing changed. */ + | { kind: 'failed' }; + /** - * Attempt to re-authenticate interactively. - * - * The caller replays the original request with the returned token, so the new - * session must belong to the same account as the expired one. If the user - * signs in as a different account the new credentials are saved but `null` - * is returned, and the pending request is not replayed. + * Whether the new session provably belongs to the account of the expired one. + * Fails closed: compares user IDs when both are known, otherwise the emails + * the server returned; with nothing to compare, the answer is "no" (M-366). + */ +function provablySameAccount( + old: { userId?: string; email?: string } | null | undefined, + next: { id?: string; email?: string }, +): boolean { + if (old?.userId && next.id) return String(old.userId) === String(next.id); + if (old?.email && next.email) return old.email.toLowerCase() === next.email.toLowerCase(); + return false; +} + +/** The identities are known on both sides and differ. */ +function provablyDifferentAccount( + old: { userId?: string; email?: string } | null | undefined, + next: { id?: string; email?: string }, +): boolean { + if (old?.userId && next.id && String(old.userId) !== String(next.id)) return true; + return !!old?.email && !!next.email && old.email.toLowerCase() !== next.email.toLowerCase(); +} + +/** + * Attempt to re-authenticate interactively after a 401. * - * @returns The new access token on success, or `null` on failure / user decline / - * account change. + * The original request was rejected by the server, so nothing was executed. + * It is only sent again automatically when it is a read (`replayable`) and the + * new session provably belongs to the same account. A write — a swap, + * transfer, order, cancellation, account change — is never replayed: the + * user re-runs the command and goes through its confirmation again with + * current quotes and prices (M-366). */ -export async function attemptReAuth(): Promise { +export async function attemptReAuth(opts: { replayable?: boolean } = {}): Promise { try { console.log(''); console.log( @@ -40,7 +74,7 @@ export async function attemptReAuth(): Promise { if (!wantReLogin) { console.log(chalk.dim('Run `minara login` to manually refresh your session.')); - return null; + return { kind: 'failed' }; } // ── Determine email ───────────────────────────────────────────────── const creds = loadCredentials(); @@ -63,7 +97,7 @@ export async function attemptReAuth(): Promise { chalk.red('✖'), `Failed to send code: ${codeRes.error?.message ?? 'Unknown error'}`, ); - return null; + return { kind: 'failed' }; } console.log(chalk.green('✔'), `Verification code sent to ${chalk.cyan(email)}`); @@ -87,7 +121,7 @@ export async function attemptReAuth(): Promise { chalk.red('✖'), `Verification failed: ${verifyRes.error?.message ?? 'Invalid code'}`, ); - return null; + return { kind: 'failed' }; } const user = verifyRes.data; @@ -95,7 +129,7 @@ export async function attemptReAuth(): Promise { if (!newToken) { console.error(chalk.red('✖'), 'No access token in response.'); - return null; + return { kind: 'failed' }; } const newEmail = user.email ?? email; @@ -108,23 +142,36 @@ export async function attemptReAuth(): Promise { displayName: user.displayName, }); - // ── Only replay the original request for the same account ─────────── - const userChanged = creds?.userId !== undefined && user.id !== undefined && creds.userId !== user.id; - const emailChanged = !!creds?.email && !!newEmail && creds.email.toLowerCase() !== newEmail.toLowerCase(); - if (userChanged || emailChanged) { - console.log( - chalk.yellow('⚠'), - chalk.yellow(`Signed in as a different account (${newEmail}). The pending request was NOT retried.`), - ); - console.log(chalk.dim('Run the command again if you want to perform it with this account.')); + // ── Decide whether the original request may be sent again ─────────── + // Only the server's answer counts as the new identity, not the email + // typed or remembered locally. + const next = { id: user.id, email: user.email }; + if (provablyDifferentAccount(creds, next)) { + const message = `Signed in as a different account (${newEmail}). The pending request was NOT retried. ` + + 'Run the command again if you want to perform it with this account.'; + console.log(chalk.yellow('⚠'), chalk.yellow(message)); + console.log(''); + return { kind: 'renewed', message }; + } + if (!provablySameAccount(creds, next)) { + const message = 'Signed in again, but the new session could not be matched to the expired one, ' + + 'so the pending request was NOT retried. Run the command again.'; + console.log(chalk.yellow('⚠'), chalk.yellow(message)); + console.log(''); + return { kind: 'renewed', message }; + } + if (!opts.replayable) { + const message = 'Signed in again. The pending request changes your account (e.g. a trade, transfer or order), ' + + 'so it was NOT sent automatically. Run the command again to review and confirm it with current prices.'; + console.log(chalk.green('✔'), message); console.log(''); - return null; + return { kind: 'renewed', message, token: newToken }; } console.log(chalk.green('✔'), 'Re-login successful! Retrying your request…'); console.log(''); - return newToken; + return { kind: 'retry', token: newToken }; } catch (err) { // Handle Ctrl+C or closed prompt if (err instanceof Error && (err.message.includes('closed') || err.message.includes('aborted'))) { @@ -135,6 +182,6 @@ export async function attemptReAuth(): Promise { `Re-login error: ${err instanceof Error ? err.message : String(err)}`, ); } - return null; + return { kind: 'failed' }; } } diff --git a/src/utils.ts b/src/utils.ts index ec1460f..1daffcd 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -212,16 +212,55 @@ export function parseChainOption(raw: string): Chain { return chain; } -// Chain-agnostic placeholders used for EVM native tokens +// Placeholders for "the native token of the chain the request is sent on" const EVM_NATIVE_PLACEHOLDER_RE = /^0x(0{40}|e{40})$/i; +export function isEvmNativePlaceholder(address?: string | null): boolean { + return !!address && EVM_NATIVE_PLACEHOLDER_RE.test(address); +} + +/** Native token symbol(s) per chain. */ +export const NATIVE_SYMBOLS: Partial> = { + ethereum: ['ETH'], base: ['ETH'], arbitrum: ['ETH'], optimism: ['ETH'], + blast: ['ETH'], manta: ['ETH'], mode: ['ETH'], + polygon: ['POL', 'MATIC'], polymarket: ['POL', 'MATIC'], + avalanche: ['AVAX'], bsc: ['BNB'], berachain: ['BERA'], sonic: ['S'], + conflux: ['CFX'], merlin: ['BTC'], monad: ['MON'], xlayer: ['OKB'], + solana: ['SOL'], +}; + +/** + * Whether an EVM native placeholder entry (0x0…0 / 0xE…E) may be used on + * `chain`. The placeholder always executes as the native token of the chain + * the request is sent on, so the entry is only accepted when its symbol is + * that native token — ETH listed on Ethereum may be used on Base, but $POL + * must never be shown for a request that would spend ETH on Base (M-365). + * Without a symbol, only an entry listed on that same chain is trusted. + * EVM placeholders are never valid on Solana. + */ +export function placeholderFitsChain(token: { symbol?: string | null; chain?: string | null }, chain: Chain): boolean { + if (chain === 'solana') return false; + const sym = token.symbol?.trim().toUpperCase(); + if (sym) return (NATIVE_SYMBOLS[chain] ?? []).includes(sym); + return normalizeChain(token.chain ?? undefined) === chain; +} + /** * Throw if the token's own chain is known and differs from the chain the * request will be sent on (e.g. `--chain ethereum` with a Base-only token). - * EVM native-token placeholders (0x0…0 / 0xE…E) are chain-agnostic and skipped. + * An EVM native placeholder (0x0…0 / 0xE…E) is accepted only when it stands + * for the native token of that chain (see {@link placeholderFitsChain}). */ export function assertTokenOnChain(token: TokenDisplayInfo, chain: Chain): void { - if (EVM_NATIVE_PLACEHOLDER_RE.test(token.address)) return; + if (isEvmNativePlaceholder(token.address)) { + if (placeholderFitsChain(token, chain)) return; + const label = token.symbol ? `$${sanitizeTerminal(token.symbol)}` : 'This native-token placeholder'; + const natives = (NATIVE_SYMBOLS[chain] ?? []).map((n) => `$${n}`).join(' / ') || 'its own native token'; + throw new Error( + `${label} (${sanitizeTerminal(token.address)}) would execute as the native token of ${displayChain(chain)} ` + + `(${natives}), not ${label}. Pick the token on the intended chain or change --chain.`, + ); + } const tokenChain = normalizeChain(token.chain); if (tokenChain && tokenChain !== chain) { const label = token.symbol ? `$${sanitizeTerminal(token.symbol)}` : sanitizeTerminal(token.address); @@ -294,8 +333,10 @@ export interface LookupTokenOptions { * - Otherwise the raw input is sent to the search API and may match by * address, ticker, or name. A single result is only accepted silently when * its address or symbol matches the input exactly. - * - When `opts.chain` is given, candidates on other chains are dropped - * (EVM native placeholders 0x0…0 / 0xE…E are chain-agnostic and kept). + * - When `opts.chain` is given, candidates on other chains are dropped. An + * EVM native placeholder (0x0…0 / 0xE…E) is kept only when its symbol is + * that chain's native token, and is then shown on that chain; typing the + * placeholder itself resolves to the chain's native token directly. * * When several candidates remain the user is prompted to pick one. Choices * show the full contract address and market cap, sorted by chain gas cost @@ -309,6 +350,25 @@ export async function lookupToken(tokenInput: string, opts: LookupTokenOptions = const kw = keyword.toLowerCase(); const wantChain = opts.chain; + // An explicit native placeholder (0x0…0 / 0xE…E) with a known chain means + // "the native token of that chain": resolve it directly instead of picking + // another chain's native entry from the search results (M-365). + if (!isTicker && wantChain && isEvmNativePlaceholder(keyword)) { + if (wantChain === 'solana') { + throw new Error( + `${sanitizeTerminal(keyword)} is an EVM native-token placeholder and is not valid on Solana. ` + + `Use $SOL or ${resolveNativeAddress('solana')}.`, + ); + } + const native = NATIVE_SYMBOLS[wantChain]?.[0]; + return { + symbol: native, + name: `${displayChain(wantChain)} native token`, + address: keyword, + chain: wantChain, + }; + } + const spin = spinner('Looking up token…'); try { const { searchTokens } = await import('./api/tokens.js'); @@ -330,9 +390,11 @@ export async function lookupToken(tokenInput: string, opts: LookupTokenOptions = name: t.name === undefined || t.name === null ? t.name : cleanTokenText(t.name, TOKEN_NAME_MAX), })); + // A native placeholder executes on the requested chain: show and rank it there + const chainOf = (t: typeof tokens[number]) => + (wantChain && isEvmNativePlaceholder(t.address) ? wantChain : t.chain); const toInfo = (t: typeof tokens[number]): TokenDisplayInfo => { - const placeholder = !!t.address && EVM_NATIVE_PLACEHOLDER_RE.test(t.address); - const chain = placeholder && wantChain ? wantChain : t.chain; + const chain = chainOf(t); return { symbol: t.symbol, name: t.name ?? displayChain(chain), @@ -340,10 +402,12 @@ export async function lookupToken(tokenInput: string, opts: LookupTokenOptions = chain, }; }; - const onWantedChain = (t: typeof tokens[number]) => - !wantChain - || normalizeChain(t.chain) === wantChain - || (!!t.address && EVM_NATIVE_PLACEHOLDER_RE.test(t.address)); + const onWantedChain = (t: typeof tokens[number]) => { + if (!wantChain) return true; + // Another chain's native placeholder only fits when it is the same coin + if (isEvmNativePlaceholder(t.address)) return placeholderFitsChain(t, wantChain); + return normalizeChain(t.chain) === wantChain; + }; const chainList = (list: typeof tokens) => [...new Set(list.map((t) => displayChain(t.chain)).filter(Boolean))].join(', '); @@ -398,11 +462,11 @@ export async function lookupToken(tokenInput: string, opts: LookupTokenOptions = return Number.isFinite(v) ? v : -1; }; const sorted = [...tokens].sort( - (a, b) => chainGasRank(a.chain) - chainGasRank(b.chain) || mcap(b) - mcap(a), + (a, b) => chainGasRank(chainOf(a)) - chainGasRank(chainOf(b)) || mcap(b) - mcap(a), ); const perChain = new Map(); for (const t of sorted) { - const c = normalizeChain(t.chain) ?? String(t.chain ?? ''); + const c = normalizeChain(chainOf(t)) ?? String(chainOf(t) ?? ''); perChain.set(c, (perChain.get(c) ?? 0) + 1); } const crowded = [...perChain.entries()].filter(([, n]) => n > 1); @@ -417,12 +481,12 @@ export async function lookupToken(tokenInput: string, opts: LookupTokenOptions = warn(`${n} different tokens use this symbol on ${displayChain(c)} — check the full contract address and market cap.`); } - const firstChainUnique = (perChain.get(normalizeChain(sorted[0].chain) ?? String(sorted[0].chain ?? '')) ?? 0) === 1; + const firstChainUnique = (perChain.get(normalizeChain(chainOf(sorted[0])) ?? String(chainOf(sorted[0]) ?? '')) ?? 0) === 1; const selected = await select({ message: sameSymbol ? 'Select token (check the contract address):' : 'Select the correct token:', choices: sorted.map((t, i) => { const sym = t.symbol ? chalk.bold('$' + t.symbol) : '?'; - const chainName = displayChain(t.chain); + const chainName = displayChain(chainOf(t)); const name = t.name ? ` — ${t.name}` : ''; const tag = sameSymbol && i === 0 && firstChainUnique ? chalk.green(' (lowest gas)') : ''; const addr = t.address ? chalk.yellow(sanitizeTerminal(t.address)) : chalk.dim('(native token)'); diff --git a/tests/api/client-auth.test.ts b/tests/api/client-auth.test.ts index 430324c..8c4e53c 100644 --- a/tests/api/client-auth.test.ts +++ b/tests/api/client-auth.test.ts @@ -80,110 +80,118 @@ describe('client 401 auto-reauth', () => { // ── 401 with token in TTY → triggers re-auth ──────────────────────── - it('should trigger re-auth and retry on 401 in TTY mode', async () => { - Object.defineProperty(process.stdin, 'isTTY', { - value: true, - writable: true, - configurable: true, - }); + function tty() { + Object.defineProperty(process.stdin, 'isTTY', { value: true, writable: true, configurable: true }); + } - // First call: 401 (expired token) - // Second call (retry): 200 (new token works) + it('should re-auth and retry a GET (read) on 401 in TTY mode', async () => { + tty(); mockFetch .mockResolvedValueOnce(jsonResponse({ message: 'Token expired' }, 401)) .mockResolvedValueOnce(jsonResponse({ data: { id: 1, name: 'success' } })); - - mockAttemptReAuth.mockResolvedValue('fresh-new-token'); + mockAttemptReAuth.mockResolvedValue({ kind: 'retry', token: 'fresh-new-token' }); const res = await get<{ id: number; name: string }>('/me', { token: 'old-expired-token' }); - // Should have succeeded on retry expect(res.success).toBe(true); expect(res.data).toEqual({ id: 1, name: 'success' }); - - // attemptReAuth was called - expect(mockAttemptReAuth).toHaveBeenCalledOnce(); - - // Second fetch call should use the new token + expect(mockAttemptReAuth).toHaveBeenCalledWith({ replayable: true }); expect(mockFetch).toHaveBeenCalledTimes(2); - const retryInit = mockFetch.mock.calls[1][1] as RequestInit; - const retryHeaders = retryInit.headers as Record; + const retryHeaders = (mockFetch.mock.calls[1][1] as RequestInit).headers as Record; expect(retryHeaders['Authorization']).toBe('Bearer fresh-new-token'); }); - // ── User declines re-auth → returns 401 error ──────────────────────── - it('should return 401 error when user declines re-auth', async () => { - Object.defineProperty(process.stdin, 'isTTY', { - value: true, - writable: true, - configurable: true, - }); - + tty(); mockFetch.mockResolvedValue(jsonResponse({ message: 'Token expired' }, 401)); - mockAttemptReAuth.mockResolvedValue(null); // user declined + mockAttemptReAuth.mockResolvedValue({ kind: 'failed' }); const res = await get('/protected', { token: 'expired-token' }); expect(res.success).toBe(false); expect(res.error?.code).toBe(401); - expect(mockAttemptReAuth).toHaveBeenCalledOnce(); + expect(res.error?.message).toMatch(/minara login/); expect(mockFetch).toHaveBeenCalledTimes(1); // no retry }); - // ── Re-auth succeeds but retry also fails → no infinite loop ──────── - it('should not trigger re-auth again if retry also returns 401', async () => { - Object.defineProperty(process.stdin, 'isTTY', { - value: true, - writable: true, - configurable: true, - }); - - // Both calls return 401 + tty(); mockFetch .mockResolvedValueOnce(jsonResponse({ message: 'Token expired' }, 401)) .mockResolvedValueOnce(jsonResponse({ message: 'Still unauthorized' }, 401)); - - mockAttemptReAuth.mockResolvedValue('supposedly-new-token'); + mockAttemptReAuth.mockResolvedValue({ kind: 'retry', token: 'supposedly-new-token' }); const res = await get('/protected', { token: 'bad-token' }); - // Should return the retry's 401 error (not loop) expect(res.success).toBe(false); expect(res.error?.code).toBe(401); - - // Re-auth only called ONCE expect(mockAttemptReAuth).toHaveBeenCalledOnce(); - // Fetch called exactly twice: original + retry expect(mockFetch).toHaveBeenCalledTimes(2); }); - // ── POST with body retries correctly ──────────────────────────────── + // ── M-366: writes are never replayed ──────────────────────────────── - it('should preserve request body when retrying after re-auth', async () => { - Object.defineProperty(process.stdin, 'isTTY', { - value: true, - writable: true, - configurable: true, - }); + it('never replays a write (POST) after re-login: the user must re-run and re-confirm', async () => { + tty(); + mockFetch.mockResolvedValueOnce(jsonResponse({ message: 'Token expired' }, 401)); + mockAttemptReAuth.mockResolvedValue({ kind: 'renewed', message: 'Signed in again. Run the command again.', token: 'fresh-w' }); + + const res = await post('/v1/tx/cross-chain/swaps', { token: 'old-w', body: { amount: 100 } }); + expect(mockAttemptReAuth).toHaveBeenCalledWith({ replayable: false }); + expect(res.success).toBe(false); + expect(res.error).toEqual({ code: 401, message: 'Signed in again. Run the command again.' }); + expect(mockFetch).toHaveBeenCalledTimes(1); // the swap was never sent again + }); + + it('replays a read-only POST marked replayable, keeping its body', async () => { + tty(); mockFetch .mockResolvedValueOnce(jsonResponse({}, 401)) .mockResolvedValueOnce(jsonResponse({ data: { ok: true } })); + mockAttemptReAuth.mockResolvedValue({ kind: 'retry', token: 'new-token-r' }); - mockAttemptReAuth.mockResolvedValue('new-token'); - - const res = await post('/api/action', { - token: 'old-token', - body: { amount: 100, chain: 'solana' }, + const res = await post('/v1/tx/cross-chain/swaps-simulate', { + token: 'old-token-r', body: { amount: 100, chain: 'solana' }, replayable: true, }); + expect(mockAttemptReAuth).toHaveBeenCalledWith({ replayable: true }); expect(res.success).toBe(true); - - // Verify the retry preserved the POST body const retryInit = mockFetch.mock.calls[1][1] as RequestInit; expect(retryInit.method).toBe('POST'); expect(retryInit.body).toBe(JSON.stringify({ amount: 100, chain: 'solana' })); }); + + it('after a same-account re-login, later requests of the command use the new token without prompting again', async () => { + tty(); + mockFetch + .mockResolvedValueOnce(jsonResponse({}, 401)) // quote with the expired token + .mockResolvedValueOnce(jsonResponse({ data: { quote: 1 } })) // quote retried with the new token + .mockResolvedValueOnce(jsonResponse({ data: { txId: 'tx' } })); // swap, sent once, after confirmation + mockAttemptReAuth.mockResolvedValue({ kind: 'retry', token: 'renewed-s' }); + + await post('/v1/tx/cross-chain/swaps-simulate', { token: 'expired-s', replayable: true }); + const swap = await post('/v1/tx/cross-chain/swaps', { token: 'expired-s', body: { amount: 1 } }); + + expect(swap.success).toBe(true); + expect(mockAttemptReAuth).toHaveBeenCalledOnce(); + const swapHeaders = (mockFetch.mock.calls[2][1] as RequestInit).headers as Record; + expect(swapHeaders['Authorization']).toBe('Bearer renewed-s'); + }); + + it('does not carry a token over to later requests when the account could not be confirmed', async () => { + tty(); + mockFetch + .mockResolvedValueOnce(jsonResponse({}, 401)) + .mockResolvedValueOnce(jsonResponse({}, 401)); + mockAttemptReAuth + .mockResolvedValueOnce({ kind: 'renewed', message: 'could not be matched' }) + .mockResolvedValueOnce({ kind: 'failed' }); + + await get('/me', { token: 'expired-u' }); + await post('/v1/tx/cross-chain/swaps', { token: 'expired-u' }); + + const headers = (mockFetch.mock.calls[1][1] as RequestInit).headers as Record; + expect(headers['Authorization']).toBe('Bearer expired-u'); + }); }); diff --git a/tests/api/crosschain.test.ts b/tests/api/crosschain.test.ts index dfeb49f..8c518b3 100644 --- a/tests/api/crosschain.test.ts +++ b/tests/api/crosschain.test.ts @@ -66,6 +66,7 @@ describe('crosschain API', () => { await swapsSimulate('tk', list); expect(mockPost).toHaveBeenCalledWith('/v1/tx/cross-chain/swaps-simulate', { + replayable: true, token: 'tk', body: { swaps: list }, }); @@ -95,6 +96,7 @@ describe('crosschain API', () => { await getActivities('tk', dto); expect(mockPost).toHaveBeenCalledWith('/v1/tx/cross-chain/activities', { + replayable: true, token: 'tk', body: dto, }); @@ -117,6 +119,7 @@ describe('crosschain API', () => { await getStatuses('tk', ['tx1', 'tx2']); expect(mockPost).toHaveBeenCalledWith('/v1/tx/cross-chain/statuses', { + replayable: true, token: 'tk', body: { transactionIds: ['tx1', 'tx2'] }, }); diff --git a/tests/api/perps.test.ts b/tests/api/perps.test.ts index 0aa2a0e..ddecd17 100644 --- a/tests/api/perps.test.ts +++ b/tests/api/perps.test.ts @@ -280,7 +280,7 @@ describe('autopilot API', () => { const dto = { symbol: 'ETH', startTime: 1700000000000 }; await perps.priceAnalysis('tk', dto); expect(mockPost).toHaveBeenCalledWith('/tokens/price-analysis', { - token: 'tk', body: dto, + token: 'tk', body: dto, replayable: true, }); }); }); diff --git a/tests/auth-refresh.test.ts b/tests/auth-refresh.test.ts index 785fcbf..417dacb 100644 --- a/tests/auth-refresh.test.ts +++ b/tests/auth-refresh.test.ts @@ -41,189 +41,148 @@ beforeEach(() => { }); describe('attemptReAuth', () => { - // ── User declines re-login ──────────────────────────────────────────── + /** Walk through a successful email-code login returning `user`. */ + function loginAs(saved: Record, user: Record) { + mockConfirm.mockResolvedValueOnce(true); + mockLoadCredentials.mockReturnValue({ accessToken: 'old', ...saved }); + mockSendEmailCode.mockResolvedValue({ success: true }); + if (!saved.email) mockInput.mockResolvedValueOnce(user.email ?? 'typed@test.com'); + mockInput.mockResolvedValueOnce('123456'); + mockVerifyEmailCode.mockResolvedValue({ success: true, data: user as never }); + } - it('should return null when user declines re-login', async () => { + it('fails when the user declines re-login', async () => { mockConfirm.mockResolvedValueOnce(false); const { attemptReAuth } = await import('../src/auth-refresh.js'); - const result = await attemptReAuth(); - - expect(result).toBeNull(); + expect(await attemptReAuth({ replayable: true })).toEqual({ kind: 'failed' }); expect(mockSendEmailCode).not.toHaveBeenCalled(); }); - // ── Full successful re-auth flow ────────────────────────────────────── - - it('should return new token on successful re-auth (email from saved creds)', async () => { - mockConfirm.mockResolvedValueOnce(true); // yes, re-login - mockLoadCredentials.mockReturnValue({ accessToken: 'old', email: 'saved@test.com' }); - mockSendEmailCode.mockResolvedValue({ success: true }); - mockInput.mockResolvedValueOnce('123456'); // verification code - mockVerifyEmailCode.mockResolvedValue({ - success: true, - data: { - id: 'u1', - access_token: 'new-fresh-token', - email: 'saved@test.com', - displayName: 'TestUser', - }, - }); + it('retries a read when the same user id signs in again', async () => { + loginAs({ userId: 'u1', email: 'saved@test.com' }, { id: 'u1', access_token: 'new-fresh-token', email: 'saved@test.com', displayName: 'TestUser' }); const { attemptReAuth } = await import('../src/auth-refresh.js'); - const result = await attemptReAuth(); + expect(await attemptReAuth({ replayable: true })).toEqual({ kind: 'retry', token: 'new-fresh-token' }); - expect(result).toBe('new-fresh-token'); - - // Should have saved new credentials expect(mockSaveCredentials).toHaveBeenCalledWith({ accessToken: 'new-fresh-token', userId: 'u1', email: 'saved@test.com', displayName: 'TestUser', }); + expect(mockSendEmailCode).toHaveBeenCalledWith({ email: 'saved@test.com', platform: 'web' }); + }); - // Should have used saved email - expect(mockSendEmailCode).toHaveBeenCalledWith({ - email: 'saved@test.com', - platform: 'web', - }); + it('never replays a write, even for the same account (M-366)', async () => { + loginAs({ userId: 'u1', email: 'me@test.com' }, { id: 'u1', access_token: 'fresh', email: 'me@test.com' }); + + const { attemptReAuth } = await import('../src/auth-refresh.js'); + const outcome = await attemptReAuth({ replayable: false }); + + expect(outcome.kind).toBe('renewed'); + expect(outcome).toMatchObject({ token: 'fresh' }); // same account: later requests may use it + expect((outcome as { message: string }).message).toMatch(/NOT sent automatically.*run the command again/i); }); - // ── Email not in saved creds → prompt user ────────────────────────── + it('defaults to treating the request as a write', async () => { + loginAs({ userId: 'u1' }, { id: 'u1', access_token: 'fresh', email: 'me@test.com' }); - it('should prompt for email when not in saved credentials', async () => { - mockConfirm.mockResolvedValueOnce(true); - mockLoadCredentials.mockReturnValue({ accessToken: 'old' }); // no email - mockInput - .mockResolvedValueOnce('manual@test.com') // email prompt - .mockResolvedValueOnce('654321'); // code prompt - mockSendEmailCode.mockResolvedValue({ success: true }); - mockVerifyEmailCode.mockResolvedValue({ - success: true, - data: { id: 'u2', access_token: 'manual-token' }, - }); + const { attemptReAuth } = await import('../src/auth-refresh.js'); + expect((await attemptReAuth()).kind).toBe('renewed'); + }); + + it('fails closed when the old credentials carry no identity (M-366)', async () => { + loginAs({}, { id: 'u2', access_token: 'manual-token', email: 'typed@test.com' }); const { attemptReAuth } = await import('../src/auth-refresh.js'); - const result = await attemptReAuth(); + const outcome = await attemptReAuth({ replayable: true }); + + expect(outcome.kind).toBe('renewed'); + expect(outcome).not.toHaveProperty('token'); + expect((outcome as { message: string }).message).toMatch(/could not be matched/); + expect(mockSendEmailCode).toHaveBeenCalledWith({ email: 'typed@test.com', platform: 'web' }); + // the user did authenticate, so the new session is kept + expect(mockSaveCredentials).toHaveBeenCalledWith(expect.objectContaining({ accessToken: 'manual-token' })); + }); - expect(result).toBe('manual-token'); - expect(mockSendEmailCode).toHaveBeenCalledWith({ - email: 'manual@test.com', - platform: 'web', - }); + it('fails closed when the server returns no identity (M-366)', async () => { + loginAs({ userId: 'u1', email: 'me@test.com' }, { access_token: 'fresh' }); + + const { attemptReAuth } = await import('../src/auth-refresh.js'); + const outcome = await attemptReAuth({ replayable: true }); + expect(outcome.kind).toBe('renewed'); + expect(outcome).not.toHaveProperty('token'); }); - // ── Account changed during re-login → do not replay ────────────────── + it('uses the server-returned email, not the remembered one, when user ids are missing', async () => { + loginAs({ email: 'me@test.com' }, { access_token: 'fresh', email: 'ME@test.com' }); - it('should return null (no retry) when re-login yields a different user id', async () => { - mockConfirm.mockResolvedValueOnce(true); - mockLoadCredentials.mockReturnValue({ accessToken: 'old', userId: 'u-original', email: 'me@test.com' }); - mockSendEmailCode.mockResolvedValue({ success: true }); - mockInput.mockResolvedValueOnce('123456'); - mockVerifyEmailCode.mockResolvedValue({ - success: true, - data: { id: 'u-other', access_token: 'other-token', email: 'me@test.com' }, - }); + const { attemptReAuth } = await import('../src/auth-refresh.js'); + expect(await attemptReAuth({ replayable: true })).toEqual({ kind: 'retry', token: 'fresh' }); + }); + + it('does not replay when a different user id signs in', async () => { + loginAs({ userId: 'u-original', email: 'me@test.com' }, { id: 'u-other', access_token: 'other-token', email: 'me@test.com' }); const { attemptReAuth } = await import('../src/auth-refresh.js'); - const result = await attemptReAuth(); + const outcome = await attemptReAuth({ replayable: true }); - expect(result).toBeNull(); - // New session is still saved — the user did authenticate + expect(outcome.kind).toBe('renewed'); + expect(outcome).not.toHaveProperty('token'); + expect((outcome as { message: string }).message).toMatch(/different account/); expect(mockSaveCredentials).toHaveBeenCalledWith(expect.objectContaining({ accessToken: 'other-token', userId: 'u-other' })); }); - it('should return null (no retry) when re-login yields a different email', async () => { - mockConfirm.mockResolvedValueOnce(true); - mockLoadCredentials.mockReturnValue({ accessToken: 'old', email: 'me@test.com' }); - mockSendEmailCode.mockResolvedValue({ success: true }); - mockInput.mockResolvedValueOnce('123456'); - mockVerifyEmailCode.mockResolvedValue({ - success: true, - data: { id: 'u9', access_token: 'other-token', email: 'someone-else@test.com' }, - }); + it('does not replay when a different email signs in', async () => { + loginAs({ email: 'me@test.com' }, { id: 'u9', access_token: 'other-token', email: 'someone-else@test.com' }); const { attemptReAuth } = await import('../src/auth-refresh.js'); - expect(await attemptReAuth()).toBeNull(); + const outcome = await attemptReAuth({ replayable: true }); + expect(outcome.kind).toBe('renewed'); + expect((outcome as { message: string }).message).toMatch(/different account/); }); - it('should treat email case differences as the same account', async () => { - mockConfirm.mockResolvedValueOnce(true); - mockLoadCredentials.mockReturnValue({ accessToken: 'old', userId: 'u1', email: 'Me@Test.com' }); - mockSendEmailCode.mockResolvedValue({ success: true }); - mockInput.mockResolvedValueOnce('123456'); - mockVerifyEmailCode.mockResolvedValue({ - success: true, - data: { id: 'u1', access_token: 'fresh', email: 'me@test.com' }, - }); + it('treats email case differences as the same account', async () => { + loginAs({ userId: 'u1', email: 'Me@Test.com' }, { id: 'u1', access_token: 'fresh', email: 'me@test.com' }); const { attemptReAuth } = await import('../src/auth-refresh.js'); - expect(await attemptReAuth()).toBe('fresh'); + expect(await attemptReAuth({ replayable: true })).toEqual({ kind: 'retry', token: 'fresh' }); }); - // ── sendEmailCode fails ─────────────────────────────────────────────── - - it('should return null when sending email code fails', async () => { + it('fails when sending the email code fails', async () => { mockConfirm.mockResolvedValueOnce(true); mockLoadCredentials.mockReturnValue({ accessToken: 'old', email: 'user@test.com' }); - mockSendEmailCode.mockResolvedValue({ - success: false, - error: { code: 429, message: 'Rate limited' }, - }); + mockSendEmailCode.mockResolvedValue({ success: false, error: { code: 429, message: 'Rate limited' } }); const { attemptReAuth } = await import('../src/auth-refresh.js'); - const result = await attemptReAuth(); - - expect(result).toBeNull(); + expect(await attemptReAuth({ replayable: true })).toEqual({ kind: 'failed' }); expect(mockVerifyEmailCode).not.toHaveBeenCalled(); }); - // ── verifyEmailCode fails ───────────────────────────────────────────── - - it('should return null when verification fails', async () => { + it('fails when verification fails', async () => { mockConfirm.mockResolvedValueOnce(true); mockLoadCredentials.mockReturnValue({ accessToken: 'old', email: 'user@test.com' }); mockSendEmailCode.mockResolvedValue({ success: true }); mockInput.mockResolvedValueOnce('wrong-code'); - mockVerifyEmailCode.mockResolvedValue({ - success: false, - error: { code: 400, message: 'Invalid code' }, - }); + mockVerifyEmailCode.mockResolvedValue({ success: false, error: { code: 400, message: 'Invalid code' } }); const { attemptReAuth } = await import('../src/auth-refresh.js'); - const result = await attemptReAuth(); - - expect(result).toBeNull(); + expect(await attemptReAuth({ replayable: true })).toEqual({ kind: 'failed' }); expect(mockSaveCredentials).not.toHaveBeenCalled(); }); - // ── No access_token in verify response ────────────────────────────── - - it('should return null when no access_token in response', async () => { - mockConfirm.mockResolvedValueOnce(true); - mockLoadCredentials.mockReturnValue({ accessToken: 'old', email: 'user@test.com' }); - mockSendEmailCode.mockResolvedValue({ success: true }); - mockInput.mockResolvedValueOnce('123456'); - mockVerifyEmailCode.mockResolvedValue({ - success: true, - data: { id: 'u1' }, // no access_token field - }); + it('fails when the response has no access_token', async () => { + loginAs({ userId: 'u1', email: 'user@test.com' }, { id: 'u1' }); const { attemptReAuth } = await import('../src/auth-refresh.js'); - const result = await attemptReAuth(); - - expect(result).toBeNull(); + expect(await attemptReAuth({ replayable: true })).toEqual({ kind: 'failed' }); }); - // ── User cancels prompt (Ctrl+C) ───────────────────────────────────── - - it('should handle prompt cancellation gracefully', async () => { + it('handles prompt cancellation gracefully', async () => { mockConfirm.mockRejectedValueOnce(new Error('Prompt was closed')); const { attemptReAuth } = await import('../src/auth-refresh.js'); - const result = await attemptReAuth(); - - expect(result).toBeNull(); + expect(await attemptReAuth({ replayable: true })).toEqual({ kind: 'failed' }); }); }); diff --git a/tests/lookup-token.test.ts b/tests/lookup-token.test.ts index a50b18e..8abe6ef 100644 --- a/tests/lookup-token.test.ts +++ b/tests/lookup-token.test.ts @@ -95,6 +95,59 @@ describe('lookupToken — chain filter', () => { .rejects.toThrow(/not found on Ethereum \(found on: Solana\)/); }); + const ZERO = '0x0000000000000000000000000000000000000000'; + const EEEE = '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'; + + it('drops another chain\'s native placeholder that is not this chain\'s coin (M-365)', async () => { + mockSearch.mockResolvedValue({ + success: true, + data: [{ symbol: 'POL', name: 'Polygon Ecosystem Token', address: ZERO, chain: 'polygon' }], + }); + // Before: accepted as "$POL on Base", executed as ETH + await expect(lookupToken('$POL', { chain: 'base' })).rejects.toThrow(/not found on Base \(found on: Polygon\)/); + }); + + it('never accepts EVM native placeholders on Solana (M-365)', async () => { + mockSearch.mockResolvedValue({ + success: true, + data: [{ symbol: 'ETH', name: 'Ether', address: EEEE, chain: 'ethereum' }], + }); + await expect(lookupToken('$ETH', { chain: 'solana' })).rejects.toThrow(/not found on Solana/); + }); + + it('offers the real token, not a foreign native entry, when a chain has a token with that symbol (M-365)', async () => { + const realBaseS = { symbol: 'S', name: 'Real S on Base', address: '0x3333333333333333333333333333333333333333', chain: 'base', marketCap: 1_000_000 }; + mockSearch.mockResolvedValue({ + success: true, + data: [{ symbol: 'S', name: 'Sonic', address: ZERO, chain: 'sonic', marketCap: 9_000_000_000 }, realBaseS], + }); + const t = await lookupToken('$S', { chain: 'base' }); + expect(t).toMatchObject({ address: realBaseS.address, chain: 'base' }); + expect(mockSelect).not.toHaveBeenCalled(); + }); + + it('shows a fitting native entry on the requested chain in the picker', async () => { + mockSearch.mockResolvedValue({ + success: true, + data: [ + { symbol: 'ETH', name: 'Ether', address: ZERO, chain: 'ethereum', marketCap: 400_000_000_000 }, + { symbol: 'ETH', name: 'Fake ETH', address: '0x4444444444444444444444444444444444444444', chain: 'base', marketCap: 1_000 }, + ], + }); + mockSelect.mockImplementationOnce((async (cfg: { choices: Choice[] }) => cfg.choices[0].value) as never); + await lookupToken('$ETH', { chain: 'base' }); + const native = choicesOf().find((c) => c.name.includes(ZERO))!; + expect(native.name).toContain('[Base]'); + expect(native.name).not.toContain('[Ethereum]'); + }); + + it('resolves a typed native placeholder to the chain\'s own native token without searching', async () => { + const t = await lookupToken(ZERO, { chain: 'polygon' }); + expect(t).toEqual({ symbol: 'POL', name: 'Polygon native token', address: ZERO, chain: 'polygon' }); + expect(mockSearch).not.toHaveBeenCalled(); + await expect(lookupToken(EEEE, { chain: 'solana' })).rejects.toThrow(/not valid on Solana/); + }); + it('keeps chain-agnostic EVM native placeholders and reports the requested chain', async () => { mockSearch.mockResolvedValue({ success: true, diff --git a/tests/security-hardening.test.ts b/tests/security-hardening.test.ts index 2eaba38..1d5abfc 100644 --- a/tests/security-hardening.test.ts +++ b/tests/security-hardening.test.ts @@ -227,10 +227,23 @@ describe('parseChainOption / assertTokenOnChain', () => { expect(() => assertTokenOnChain({ symbol: 'X', address: '0xabc' }, 'base')).not.toThrow(); }); - it('skips EVM native-token placeholders, which are chain-agnostic', () => { + it('accepts an EVM native placeholder when it is that chain\'s native token', () => { expect(() => assertTokenOnChain( { symbol: 'ETH', address: '0x0000000000000000000000000000000000000000', chain: 'ethereum' }, 'base', )).not.toThrow(); + expect(() => assertTokenOnChain( + { symbol: 'POL', address: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', chain: 'polygon' }, 'polygon', + )).not.toThrow(); + }); + + it('rejects another chain\'s native placeholder that would execute as a different coin (M-365)', () => { + // $POL shown, but on Base the placeholder spends ETH + expect(() => assertTokenOnChain( + { symbol: 'POL', address: '0x0000000000000000000000000000000000000000', chain: 'polygon' }, 'base', + )).toThrow(/would execute as the native token of Base \(\$ETH\), not \$POL/); + expect(() => assertTokenOnChain( + { symbol: 'ETH', address: '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', chain: 'ethereum' }, 'solana', + )).toThrow(/native token of Solana/); }); });